返回 CodeWhale
latex_render.rs
根目录 / crates / tui / src / tui / history / latex_render.rs
1 //! LaTeX math expression rendering for the TUI transcript.
2 //! Renders `$...$` (inline) and `$$...$$` (display) math expressions using
3 //! Unicode approximations for terminal display.
4 use std::collections::HashMap;
5 use std::sync::OnceLock;
6 use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
7
8 fn is_escaped(bytes: &[u8], idx: usize) -> bool {
9 let mut slashes = 0;
10 let mut cursor = idx;
11 while cursor > 0 && bytes[cursor - 1] == b'\\' {
12 slashes += 1;
13 cursor -= 1;
14 }
15 slashes % 2 == 1
16 }
17 /// Private: find the start of math delimiter ($, $$, \(, \[) in text.
18 fn find_math_start(text: &str) -> Option<usize> {
19 let b = text.as_bytes();
20 for (idx, &byte) in b.iter().enumerate() {
21 if byte == b'$' && !is_escaped(b, idx) {
22 return Some(idx);
23 }
24 if byte == b'\\'
25 && !is_escaped(b, idx)
26 && idx + 1 < b.len()
27 && (b[idx + 1] == b'(' || b[idx + 1] == b'[')
28 {
29 return Some(idx);
30 }
31 }
32 None
33 }
34 /// Private: if text starts with a math delimiter, find closing delimiter and return (end_pos, is_display).
35 fn find_math_end(text: &str) -> Option<(usize, bool)> {
36 let b = text.as_bytes();
37 if b.starts_with(b"$$") {
38 for i in 2..b.len().saturating_sub(1) {
39 if b[i] == b'{' {
40 continue;
41 }
42 if b[i..].starts_with(b"$$") && !is_escaped(b, i) {
43 return Some((i, true));
44 }
45 }
46 } else if b.starts_with(b"$") && !b.starts_with(b"$$") {
47 if b.get(1).is_some_and(u8::is_ascii_whitespace) {
48 return None;
49 }
50 for (j, &byte) in b[1..].iter().enumerate() {
51 if byte == b'{' {
52 continue;
53 }
54 if byte == b'\n' {
55 return None;
56 }
57 let i = j + 1;
58 if byte != b'$' || is_escaped(b, i) {
59 continue;
60 }
61 let prev = text[..i].chars().next_back().unwrap_or(' ');
62 let next = b.get(i + 1).copied().unwrap_or(b' ');
63 if next == b'{'
64 || (next.is_ascii_alphanumeric()
65 && !prev.is_ascii_alphanumeric()
66 && !matches!(prev, ')' | ']' | '}')
67 && (prev.is_ascii() || prev.width() == Some(2)))
68 {
69 return None;
70 }
71 if !prev.is_ascii_whitespace() && !next.is_ascii_digit() {
72 return Some((i, false));
73 }
74 }
75 } else if b.starts_with(b"\\[") {
76 for i in 2..b.len().saturating_sub(1) {
77 if b[i] == b'{' {
78 continue;
79 }
80 if b[i..].starts_with(b"\\]") && !is_escaped(b, i) {
81 return Some((i, true));
82 }
83 }
84 } else if b.starts_with(b"\\(") {
85 for i in 2..b.len().saturating_sub(1) {
86 if b[i] == b'{' {
87 continue;
88 }
89 if b[i..].starts_with(b"\\)") && !is_escaped(b, i) {
90 return Some((i, false));
91 }
92 }
93 }
94 None
95 }
96 fn math_delim_offset(text: &str) -> usize {
97 let b = text.as_bytes();
98 if b.starts_with(b"$$") || b.starts_with(b"\\[") || b.starts_with(b"\\(") {
99 2
100 } else {
101 1
102 }
103 }
104 fn render_math_segment(text: &str) -> String {
105 let mut result = String::new();
106 let mut i = 0;
107 while i < text.len() {
108 let remaining = &text[i..];
109 if let Some((end, _is_display)) = find_math_end(remaining) {
110 let offset = math_delim_offset(remaining);
111 let inner = &remaining[offset..end];
112 result.push_str(&render_latex_to_string(inner));
113 let close_len: usize = if remaining[end..].starts_with("\\]")
114 || remaining[end..].starts_with("$$")
115 || remaining[end..].starts_with("\\)")
116 {
117 2
118 } else if remaining.as_bytes().get(end..end + 1) == Some(b"$") {
119 1
120 } else {
121 0
122 };
123 i += end + close_len;
124 } else {
125 let skip = find_math_start(remaining).unwrap_or(remaining.len());
126 if skip == 0 {
127 // Unmatched opening delimiter ($, $$, \(, \[) during streaming:
128 // push it as plain text so the loop can advance.
129 result.push(remaining.chars().next().unwrap_or('$'));
130 i += remaining.chars().next().map(|c| c.len_utf8()).unwrap_or(1);
131 } else {
132 result.push_str(&remaining[..skip]);
133 i += skip;
134 if skip == remaining.len() {
135 break;
136 }
137 }
138 }
139 }
140 result
141 }
142
143 /// Replace math delimiters with plain Unicode while preserving Markdown code.
144 ///
145 /// Fast path (#perf-r5): the overwhelming majority of streamed content
146 /// contains no math delimiters at all. A single byte scan for the three
147 /// opening delimiters (`$`, `\(`, `\[`) decides between borrowing the input
148 /// untouched and running the full transform, so the per-chunk streaming
149 /// render avoids allocating a full-content copy on every update when no
150 /// math is present.
151 pub fn render_latex_in_text(text: &str) -> std::borrow::Cow<'_, str> {
152 // Math can only start at '$' (incl. '$$') or the two-byte '\(' and '\['.
153 // Scanning bytes directly avoids a regex; any hit falls back to the
154 // full transform below, which re-verifies delimiters precisely.
155 let has_delim = text
156 .as_bytes()
157 .iter()
158 .enumerate()
159 .any(|(idx, &byte)| match byte {
160 b'$' => true,
161 b'\\' => matches!(text.as_bytes().get(idx + 1), Some(b'(') | Some(b'[')),
162 _ => false,
163 });
164 if !has_delim {
165 return std::borrow::Cow::Borrowed(text);
166 }
167 let mut result = String::with_capacity(text.len());
168 let mut cursor = 0;
169
170 while cursor < text.len() {
171 let Some(tick_offset) = text[cursor..].find('`') else {
172 result.push_str(&render_math_segment(&text[cursor..]));
173 break;
174 };
175 let tick_start = cursor + tick_offset;
176 result.push_str(&render_math_segment(&text[cursor..tick_start]));
177
178 let tick_count = text[tick_start..]
179 .bytes()
180 .take_while(|byte| *byte == b'`')
181 .count();
182 let delimiter = "`".repeat(tick_count);
183 let content_start = tick_start + tick_count;
184 if let Some(close_offset) = text[content_start..].find(&delimiter) {
185 let code_end = content_start + close_offset + tick_count;
186 result.push_str(&text[tick_start..code_end]);
187 cursor = code_end;
188 } else {
189 result.push_str(&text[tick_start..]);
190 break;
191 }
192 }
193
194 std::borrow::Cow::Owned(result)
195 }
196
197 // --- Environment rendering ---
198
199 /// Render a `\begin{name}...\end{name}` block.
200 /// `content` is everything between the braces.
201 fn render_environment(env_name: &str, content: &str) -> String {
202 match env_name {
203 "aligned" | "align" | "gather" | "eqnarray" | "split" => render_aligned(content),
204 "pmatrix" | "bmatrix" | "vmatrix" | "Bmatrix" | "matrix" | "smallmatrix" => {
205 render_matrix(env_name, content)
206 }
207 "array" => render_array(content),
208 "cases" | "dcases" => render_cases(content, false),
209 "rcases" | "drcases" => render_cases(content, true),
210 _ => {
211 // Unknown environment: pass through raw
212 format!("\\begin{{{env_name}}}{content}\\end{{{env_name}}}")
213 }
214 }
215 }
216
217 /// Split a multi-row env content into rows (`\\` separator), each rendered.
218 /// `row_fn` is called for each parsed row (list of cell strings).
219 fn parse_rows<F>(content: &str, mut row_fn: F)
220 where
221 F: FnMut(Vec<String>),
222 {
223 // Split by \\ (but be careful: \\\\ is an escaped backslash, not a line break)
224 let mut current = String::new();
225 let mut chars = content.chars().peekable();
226 while let Some(ch) = chars.next() {
227 if ch == '\\' {
228 if chars.peek() == Some(&'\\') {
229 // Line break marker
230 chars.next(); // consume second \
231 // If followed by optional whitespace and an optional * (\\*)
232 while matches!(chars.peek(), Some(&' ') | Some(&'\t')) {
233 chars.next();
234 }
235 if chars.peek() == Some(&'*') {
236 chars.next();
237 }
238 row_fn(parse_row_cells(&current));
239 current.clear();
240 } else if chars.peek() == Some(&'[') || chars.peek() == Some(&'{') {
241 // --- Spacing ---
242 // --- Spacing ---
243 if chars.peek() == Some(&'[') {
244 chars.next();
245 while let Some(&c) = chars.peek() {
246 if c == ']' {
247 chars.next();
248 break;
249 }
250 chars.next();
251 }
252 } else if chars.peek() == Some(&'{') {
253 let _ = read_braced_chars(&mut chars);
254 }
255 row_fn(parse_row_cells(&current));
256 current.clear();
257 } else {
258 current.push('\\');
259 }
260 } else if ch == '\n' {
261 // Newlines in environments often act as row separators
262 // but not inside braces
263 // Simple approach: treat bare \n as space
264 if !current.is_empty() && !current.ends_with(' ') {
265 current.push(' ');
266 }
267 } else {
268 current.push(ch);
269 }
270 }
271 // Last row
272 row_fn(parse_row_cells(&current));
273 }
274
275 /// Split a single row into cells by `&`.
276 fn parse_row_cells(row: &str) -> Vec<String> {
277 // Split by & but skip escaped \&
278 let mut cells = Vec::new();
279 let mut current = String::new();
280 let mut chars = row.chars().peekable();
281 while let Some(ch) = chars.next() {
282 if ch == '&' {
283 cells.push(current.trim().to_string());
284 current.clear();
285 } else if ch == '\\' && chars.peek() == Some(&'&') {
286 // Escaped ampersand
287 current.push('&');
288 chars.next();
289 } else {
290 current.push(ch);
291 }
292 }
293 cells.push(current.trim().to_string());
294 cells
295 }
296
297 /// Aligned equations: align at `&` markers.
298 fn render_aligned(content: &str) -> String {
299 let mut rows: Vec<Vec<String>> = Vec::new();
300 parse_rows(content, |cells| rows.push(cells));
301
302 if rows.is_empty() {
303 return String::new();
304 }
305
306 // Determine max columns
307 let max_cols = rows.iter().map(|r| r.len()).max().unwrap_or(0);
308 if max_cols == 0 {
309 return String::new();
310 }
311
312 // Double-pass: render each cell and measure widths
313 let mut rendered: Vec<Vec<String>> = Vec::new();
314 let mut col_widths: Vec<usize> = vec![0; max_cols];
315
316 for row in &rows {
317 let mut rendered_row = Vec::new();
318 for (ci, cell) in row.iter().enumerate() {
319 let rendered_cell = render_latex_to_string(cell);
320 let w = UnicodeWidthStr::width(rendered_cell.as_str());
321 if ci < max_cols && w > col_widths[ci] {
322 col_widths[ci] = w;
323 }
324 rendered_row.push(rendered_cell);
325 }
326 // Pad missing cells
327 while rendered_row.len() < max_cols {
328 rendered_row.push(String::new());
329 }
330 rendered.push(rendered_row);
331 }
332
333 // Second pass: assemble with padding
334 let mut result = String::new();
335 for (ri, row) in rendered.iter().enumerate() {
336 if ri > 0 {
337 result.push('\n');
338 }
339 for ci in 0..max_cols {
340 if ci > 0 {
341 let pad =
342 col_widths[ci - 1].saturating_sub(UnicodeWidthStr::width(row[ci - 1].as_str()));
343 for _ in 0..pad {
344 result.push(' ');
345 }
346 result.push_str(" ");
347 }
348 result.push_str(&row[ci]);
349 }
350 }
351
352 result
353 }
354
355 /// --- Brackets ---
356 fn render_matrix(env_name: &str, content: &str) -> String {
357 let mut rows: Vec<Vec<String>> = Vec::new();
358 parse_rows(content, |cells| rows.push(cells));
359
360 if rows.is_empty() {
361 return String::new();
362 }
363
364 let max_cols = rows.iter().map(|r| r.len()).max().unwrap_or(0);
365 if max_cols == 0 {
366 return String::new();
367 }
368
369 // Two-pass: render + measure
370 let mut rendered: Vec<Vec<String>> = Vec::new();
371 let mut col_widths: Vec<usize> = vec![0; max_cols];
372
373 for row in &rows {
374 let mut rendered_row = Vec::new();
375 for (ci, cell) in row.iter().enumerate() {
376 let rendered_cell = render_latex_to_string(cell);
377 let w = UnicodeWidthStr::width(rendered_cell.as_str());
378 if ci < max_cols && w > col_widths[ci] {
379 col_widths[ci] = w;
380 }
381 rendered_row.push(rendered_cell);
382 }
383 while rendered_row.len() < max_cols {
384 rendered_row.push(String::new());
385 }
386 rendered.push(rendered_row);
387 }
388
389 // Build each row with proper padding
390 let mut cell_strings: Vec<String> = Vec::new();
391 for row in &rendered {
392 let mut line = String::new();
393 for ci in 0..max_cols {
394 if ci > 0 {
395 line.push(' ');
396 }
397 let cell = &row[ci];
398 line.push_str(cell);
399 let pad = col_widths[ci].saturating_sub(UnicodeWidthStr::width(cell.as_str()));
400 for _ in 0..pad {
401 line.push(' ');
402 }
403 }
404 cell_strings.push(line);
405 }
406
407 match env_name {
408 "pmatrix" => surround_with("(", ")", &cell_strings, 1),
409 "bmatrix" => surround_with("[", "]", &cell_strings, 1),
410 "vmatrix" => surround_with("\u{2502}", "\u{2502}", &cell_strings, 1),
411 "Bmatrix" => surround_with("{", "}", &cell_strings, 1),
412 "smallmatrix" => surround_with("(", ")", &cell_strings, 0),
413 _ => {
414 // --- Brackets ---
415 let mut result = String::new();
416 for (ri, s) in cell_strings.iter().enumerate() {
417 if ri > 0 {
418 result.push('\n');
419 }
420 result.push_str(s);
421 }
422 result
423 }
424 }
425 }
426
427 /// --- Brackets ---
428 fn surround_with(left: &str, right: &str, rows: &[String], pad: usize) -> String {
429 if rows.is_empty() {
430 return format!("{left}{right}");
431 }
432 let mut result = String::new();
433 if rows.len() == 1 {
434 result.push_str(left);
435 for _ in 0..pad {
436 result.push(' ');
437 }
438 result.push_str(&rows[0]);
439 for _ in 0..pad {
440 result.push(' ');
441 }
442 result.push_str(right);
443 return result;
444 }
445 // Multi-row: brackets on their own lines
446 result.push_str(left);
447 result.push('\n');
448 for (ri, s) in rows.iter().enumerate() {
449 if ri > 0 {
450 result.push('\n');
451 }
452 for _ in 0..pad {
453 result.push(' ');
454 }
455 result.push_str(s);
456 }
457 result.push('\n');
458 result.push_str(right);
459 result
460 }
461
462 /// Array environment: parse column spec and render table with vertical bars.
463 fn render_array(content: &str) -> String {
464 let trimmed = content.trim_start();
465 let (col_spec, body) = if let Some(after_brace) = trimmed.strip_prefix('{') {
466 let close = after_brace.find('}').map(|i| i + 1).unwrap_or(0);
467 if close > 0 {
468 (&after_brace[..close], after_brace[close..].trim_start())
469 } else {
470 ("", trimmed)
471 }
472 } else {
473 ("", trimmed)
474 };
475 let mut has_vline_start = false;
476 let mut vlines = Vec::new();
477 let mut cols = Vec::new();
478 for ch in col_spec.chars() {
479 match ch {
480 'c' | 'l' | 'r' => cols.push(ch),
481 '|' => {
482 if cols.is_empty() {
483 has_vline_start = true;
484 } else {
485 vlines.push(cols.len());
486 }
487 }
488 _ => {}
489 }
490 }
491 let n = cols.len();
492 if n == 0 {
493 return body.to_string();
494 }
495 let mut rows = Vec::new();
496 parse_rows(body, |cells| rows.push(cells));
497 let mut result = String::new();
498 for (ri, row) in rows.iter().enumerate() {
499 if ri > 0 {
500 result.push('\n');
501 }
502 if has_vline_start {
503 result.push_str("| ");
504 }
505 for ci in 0..n {
506 if ci > 0 {
507 result.push(if vlines.contains(&ci) { '|' } else { ' ' });
508 result.push(' ');
509 }
510 result.push_str(&render_latex_to_string(
511 row.get(ci).unwrap_or(&String::new()),
512 ));
513 }
514 if vlines.contains(&n) || has_vline_start {
515 result.push_str(" |");
516 }
517 }
518 result
519 }
520
521 /// Piecewise functions with cases environment.
522 fn render_cases(content: &str, right_brace: bool) -> String {
523 let mut rows: Vec<Vec<String>> = Vec::new();
524 parse_rows(content, |cells| rows.push(cells));
525
526 if rows.is_empty() {
527 return String::new();
528 }
529
530 let mut rendered_rows: Vec<(String, Option<String>)> = Vec::new();
531 let mut left_width = 0;
532
533 for cells in &rows {
534 let left = render_latex_to_string(cells.first().map(|s| s.as_str()).unwrap_or(""));
535 let left_w = UnicodeWidthStr::width(left.as_str());
536 if left_w > left_width {
537 left_width = left_w;
538 }
539 let right = if cells.len() > 1 {
540 let r = render_latex_to_string(&cells[1]);
541 Some(r)
542 } else {
543 None
544 };
545 rendered_rows.push((left, right));
546 }
547
548 let n = rendered_rows.len();
549 let mut result = String::new();
550 for (ri, (left, right)) in rendered_rows.iter().enumerate() {
551 if ri > 0 {
552 result.push('\n');
553 }
554 if !right_brace {
555 result.push_str(match ri {
556 0 => "\u{23a7} ",
557 _ if ri == n - 1 => "\u{23a9} ",
558 _ => "\u{23a8} ",
559 });
560 }
561
562 // Left part + padding
563 let left_pad = left_width.saturating_sub(UnicodeWidthStr::width(left.as_str()));
564 result.push_str(left);
565 for _ in 0..left_pad {
566 result.push(' ');
567 }
568
569 if let Some(cond) = right {
570 result.push_str(", ");
571 result.push_str(cond);
572 }
573 }
574 result
575 }
576
577 // --- Helper: read_braced for chars iterator ---
578
579 fn read_braced_chars(chars: &mut std::iter::Peekable<std::str::Chars>) -> String {
580 let mut s = String::new();
581 let mut depth: u32 = 0;
582 if chars.next_if_eq(&'{').is_some() {
583 depth = 1;
584 }
585 while let Some(&c) = chars.peek() {
586 match c {
587 '{' => {
588 depth += 1;
589 s.push(c);
590 chars.next();
591 }
592 '}' => {
593 depth = depth.saturating_sub(1);
594 chars.next();
595 if depth == 0 {
596 break;
597 }
598 s.push('}');
599 }
600 _ => {
601 s.push(c);
602 chars.next();
603 }
604 }
605 }
606 s
607 }
608
609 // --- Styled symbols ---
610
611 fn render_styled_symbol(
612 command: &str,
613 chars: &mut std::iter::Peekable<std::str::Chars>,
614 out: &mut String,
615 ) {
616 let argument = read_braced_chars(chars);
617 let rendered = match (command, argument.as_str()) {
618 ("mathbb", "R") => Some("\u{211d}"),
619 ("mathbb", "C") => Some("\u{2102}"),
620 ("mathbb", "N") => Some("\u{2115}"),
621 ("mathbb", "Q") => Some("\u{211a}"),
622 ("mathbb", "Z") => Some("\u{2124}"),
623 ("mathbb", "P") => Some("\u{2119}"),
624 ("mathbb", "H") => Some("\u{210d}"),
625 ("mathbb", "F") => Some("\u{1d53b}"),
626 ("mathcal", "L") => Some("\u{2112}"),
627 ("mathcal", "H") => Some("\u{210b}"),
628 ("mathcal", "R") => Some("\u{211b}"),
629 ("mathcal", "A") => Some("\u{1d49c}"),
630 ("mathcal", "B") => Some("\u{212c}"),
631 ("mathcal", "C") => Some("\u{212d}"),
632 ("mathcal", "D") => Some("\u{1d49f}"),
633 ("mathcal", "E") => Some("\u{2130}"),
634 ("mathcal", "F") => Some("\u{2131}"),
635 ("mathcal", "I") => Some("\u{2110}"),
636 ("mathcal", "M") => Some("\u{2133}"),
637 ("mathcal", "O") => Some("\u{1d4aa}"),
638 ("mathcal", "P") => Some("\u{1d4ab}"),
639 ("mathcal", "S") => Some("\u{1d4ae}"),
640 ("mathcal", "T") => Some("\u{1d4af}"),
641 ("mathcal", "Z") => Some("\u{2128}"),
642 _ => None,
643 };
644 if let Some(symbol) = rendered {
645 out.push_str(symbol);
646 } else {
647 out.push('\\');
648 out.push_str(command);
649 out.push('{');
650 out.push_str(&argument);
651 out.push('}');
652 }
653 }
654
655 // --- Main render function ---
656
657 /// Read a braced group `{...}` from an index-based cursor in a string.
658 /// Returns (content_string, new_cursor_position).
659 fn read_braced_at(input: &str, start: usize) -> Option<(String, usize)> {
660 let bytes = input.as_bytes();
661 let mut pos = start;
662 if pos >= input.len() || bytes[pos] != b'{' {
663 return None;
664 }
665 pos += 1; // skip {
666 let mut depth: u32 = 1;
667 let mut content = String::new();
668 while pos < input.len() {
669 let ch = input[pos..].chars().next()?;
670 let byte_len = ch.len_utf8();
671 match ch {
672 '{' => {
673 depth += 1;
674 if depth > 1 {
675 content.push('{');
676 }
677 }
678 '}' => {
679 depth -= 1;
680 if depth == 0 {
681 return Some((content, pos + 1));
682 }
683 content.push('}');
684 }
685 _ => content.push(ch),
686 }
687 pos += byte_len;
688 }
689 None
690 }
691
692 /// Main LaTeX-to-Unicode rendering.
693 fn render_latex_to_string(latex: &str) -> String {
694 let input = latex.trim();
695 let mut out = String::new();
696 let mut pos = 0;
697
698 while pos < input.len() {
699 let remaining = &input[pos..];
700
701 // 1. Environment detection: \begin{name}...\end{name}
702 if let Some(env_rendered) = try_render_env(remaining) {
703 let (rendered, consumed) = env_rendered;
704 // Start multi-line envs on a fresh line for alignment
705 let needs_newline = rendered.starts_with('\u{23a7}') // cases ??
706 || rendered.starts_with('(') // pmatrix
707 || rendered.starts_with('[') // bmatrix
708 || rendered.starts_with('\u{2502}'); // vmatrix
709 if needs_newline && !out.ends_with('\n') {
710 out.push('\n');
711 }
712 out.push_str(&rendered);
713 pos += consumed;
714 continue;
715 }
716
717 let ch = remaining.chars().next().unwrap();
718 let ch_len = ch.len_utf8();
719
720 match ch {
721 '\\' => {
722 // Read command name
723 let rest = &input[pos + 1..];
724 let cmd_end = rest
725 .find(|c: char| !c.is_ascii_alphabetic())
726 .unwrap_or(rest.len());
727 let cmd = &rest[..cmd_end];
728 let _after_cmd = cmd_end;
729
730 if cmd.is_empty() {
731 // Escape sequence for special chars
732 if let Some(&next) = rest.as_bytes().first() {
733 match next {
734 b'{' | b'}' | b'$' | b'%' | b'#' | b'&' | b'_' | b' ' => {
735 // Consume the escape
736 let skip = 1 + 1; // \ + char
737 out.push(next as char);
738 pos += skip;
739 continue;
740 }
741 _ => {
742 // Unknown single-char escape 闁?output the char
743 let char_len =
744 rest.chars().next().map(|c| c.len_utf8()).unwrap_or(1);
745 out.push(rest.chars().next().unwrap_or(ch));
746 pos += 1 + char_len;
747 continue;
748 }
749 }
750 }
751 pos += 1;
752 continue;
753 }
754
755 let cmd_len = cmd.len();
756 let _total_cmd_start = pos;
757 let total_cmd_end = pos + 1 + cmd_len; // \ + name
758
759 match cmd {
760 // --- Environments (handled above, just in case) ---
761 "begin" => {
762 // Should have been caught by try_render_env above.
763 // Fallback: try inline parsing
764 if let Some((env_name, after_name)) = read_braced_at(input, total_cmd_end) {
765 let end_tag = format!("\\end{{{env_name}}}");
766 let search_from = &input[after_name..];
767 if let Some(end_rel) = search_from.find(&end_tag) {
768 let env_content = &search_from[..end_rel];
769 let rendered = render_environment(&env_name, env_content);
770 out.push_str(&rendered);
771 pos = after_name + end_rel + end_tag.len();
772 continue;
773 }
774 out.push_str(&format!("\\begin{{{env_name}}}"));
775 }
776 out.push_str("\\begin");
777 pos = total_cmd_end;
778 }
779 "end" => {
780 // Shouldn't be reached; output raw.
781 let after_end = pos + 4;
782 if let Some((env_name, after_name)) = read_braced_at(input, after_end) {
783 out.push_str(&format!("\\end{{{env_name}}}"));
784 pos = after_name;
785 } else {
786 out.push_str("\\end");
787 pos = after_end;
788 }
789 }
790 // --- Text ---
791 "text" | "mathrm" | "mathit" | "mathsf" | "textrm" | "textit" | "textbf" => {
792 if let Some((arg, new_pos)) = read_braced_at(input, total_cmd_end) {
793 out.push_str(&arg);
794 pos = new_pos;
795 } else {
796 // No braces, try single char
797 let next = &input[total_cmd_end..].chars().next();
798 if let Some(c) = next {
799 out.push(*c);
800 pos = total_cmd_end + c.len_utf8();
801 } else {
802 out.push_str(cmd);
803 pos = total_cmd_end;
804 }
805 }
806 }
807 // --- Accents ---
808 "hat" | "bar" | "tilde" | "dot" | "ddot" | "vec" | "breve" | "check"
809 | "acute" | "grave" => {
810 if let Some((arg, new_pos)) = read_braced_at(input, total_cmd_end) {
811 let rendered = render_latex_to_string(&arg);
812 let accent = match cmd {
813 "hat" => "\u{0302}",
814 "bar" => "\u{0304}",
815 "tilde" => "\u{0303}",
816 "dot" => "\u{0307}",
817 "ddot" => "\u{0308}",
818 "vec" => "\u{20d7}",
819 "breve" => "\u{0306}",
820 "check" => "\u{030c}",
821 "acute" => "\u{0301}",
822 "grave" => "\u{0300}",
823 _ => unreachable!(),
824 };
825 out.push_str(&rendered);
826 out.push_str(accent);
827 pos = new_pos;
828 } else {
829 out.push_str(&format!("\\{cmd}"));
830 pos = total_cmd_end;
831 }
832 }
833 "operatorname" => {
834 if let Some((arg, new_pos)) = read_braced_at(input, total_cmd_end) {
835 out.push_str(&arg);
836 pos = new_pos;
837 } else {
838 out.push_str("\\operatorname");
839 pos = total_cmd_end;
840 }
841 }
842 // --- Underbrace / Overbrace (passthrough) ---
843 "underbrace" | "overbrace" | "underbracket" | "overbracket" => {
844 if let Some((arg, after_arg)) = read_braced_at(input, total_cmd_end) {
845 out.push_str(&render_latex_to_string(&arg));
846 pos = after_arg;
847 } else {
848 out.push_str(&format!("\\{cmd}"));
849 pos = total_cmd_end;
850 }
851 }
852 // --- Vertical/horizontal phantom (no-op) ---
853 "vphantom" | "hphantom" | "phantom" => {
854 if let Some((_, after_arg)) = read_braced_at(input, total_cmd_end) {
855 pos = after_arg;
856 } else {
857 out.push_str(&format!("\\{cmd}"));
858 pos = total_cmd_end;
859 }
860 }
861 // --- Substack ---
862 "substack" => {
863 if let Some((arg, after_arg)) = read_braced_at(input, total_cmd_end) {
864 out.push_str(&arg);
865 pos = after_arg;
866 } else {
867 out.push_str(&format!("\\{cmd}"));
868 pos = total_cmd_end;
869 }
870 }
871 // --- Fonts ---
872 "mathbf" | "bf" => {
873 if let Some((arg, new_pos)) = read_braced_at(input, total_cmd_end) {
874 out.push_str(&render_latex_to_string(&arg));
875 pos = new_pos;
876 } else {
877 let next = &input[total_cmd_end..].chars().next();
878 if let Some(c) = next {
879 out.push(*c);
880 pos = total_cmd_end + c.len_utf8();
881 } else {
882 out.push_str(cmd);
883 pos = total_cmd_end;
884 }
885 }
886 }
887 // --- Brackets ---
888 "left" | "bigl" | "Bigl" | "biggl" | "Biggl" => {
889 // Consume the next token (bracket/pipe/dot) and output it
890 let after = &input[total_cmd_end..];
891 let delimiter = after.trim_start();
892 if let Some(next) = delimiter.chars().next() {
893 let mut skip = after.len() - delimiter.len();
894 if next != '\\' {
895 if next == '.' {
896 // \left. 闁?invisible delimiter, skip
897 } else {
898 out.push(next);
899 }
900 skip += next.len_utf8();
901 }
902 pos = total_cmd_end + skip;
903 } else {
904 pos = total_cmd_end;
905 }
906 }
907 "right" | "bigr" | "Bigr" | "biggr" | "Biggr" => {
908 let after = &input[total_cmd_end..];
909 let delimiter = after.trim_start();
910 if let Some(next) = delimiter.chars().next() {
911 let mut skip = after.len() - delimiter.len();
912 if next != '\\' {
913 if next == '.' {
914 // \right. 闁?invisible delimiter, skip
915 } else {
916 out.push(next);
917 }
918 skip += next.len_utf8();
919 }
920 pos = total_cmd_end + skip;
921 } else {
922 pos = total_cmd_end;
923 }
924 }
925 "big" | "Big" | "bigg" | "Bigg" => {
926 // Size modifiers 闁?skip them, the next token is what matters
927 let after = &input[total_cmd_end..];
928 let delimiter = after.trim_start();
929 if let Some(next) = delimiter.chars().next() {
930 let mut skip = after.len() - delimiter.len();
931 if next != '\\' {
932 out.push(next);
933 skip += next.len_utf8();
934 }
935 pos = total_cmd_end + skip;
936 } else {
937 pos = total_cmd_end;
938 }
939 }
940 // --- Spacing ---
941 "quad" => {
942 out.push_str(" ");
943 pos = total_cmd_end;
944 }
945 "qquad" => {
946 out.push_str(" ");
947 pos = total_cmd_end;
948 }
949 "," | "thinspace" => {
950 out.push(' ');
951 pos = total_cmd_end;
952 }
953 ";" | "thickspace" => {
954 out.push_str(" ");
955 pos = total_cmd_end;
956 }
957 "!" | "negthinspace" => {
958 // Negative space: just skip
959 pos = total_cmd_end;
960 }
961 ":" | "medspace" => {
962 out.push_str(" ");
963 pos = total_cmd_end;
964 }
965 " " | "space" | "enspace" => {
966 out.push(' ');
967 pos = total_cmd_end;
968 }
969 // --- Styled symbols ---
970 "mathbb" | "mathcal" => {
971 let before = out.len();
972 if let Some((arg, after_arg)) = read_braced_at(input, total_cmd_end) {
973 let mut chars = arg.chars().peekable();
974 render_styled_symbol(cmd, &mut chars, &mut out);
975 if out.len() == before {
976 // render_styled_symbol didn't match
977 out.push_str(&format!("\\{cmd}{{{arg}}}"));
978 }
979 pos = after_arg;
980 } else {
981 out.push_str(&format!("\\{cmd}"));
982 pos = total_cmd_end;
983 }
984 }
985 // --- Fractions ---
986 "frac" | "dfrac" | "tfrac" | "cfrac" => {
987 if let Some((num_s, after_num)) = read_braced_at(input, total_cmd_end) {
988 if let Some((den_s, after_den)) = read_braced_at(input, after_num) {
989 let n = render_latex_to_string(&num_s);
990 let d = render_latex_to_string(&den_s);
991 out.push_str(&format!("({n}/{d})"));
992 pos = after_den;
993 } else {
994 out.push_str(&format!("({num_s}/?)"));
995 pos = after_num;
996 }
997 } else {
998 out.push_str(&format!("\\{cmd}"));
999 pos = total_cmd_end;
1000 }
1001 }
1002 // --- Binomial coefficient ---
1003 "binom" => {
1004 if let Some((top_s, after_top)) = read_braced_at(input, total_cmd_end)
1005 && let Some((bot_s, after_bot)) = read_braced_at(input, after_top)
1006 {
1007 out.push_str(&format!(
1008 "({}/{})",
1009 render_latex_to_string(&top_s),
1010 render_latex_to_string(&bot_s)
1011 ));
1012 pos = after_bot;
1013 } else {
1014 // Malformed: keep the command literal and advance,
1015 // or the loop would re-read it forever.
1016 out.push_str("\\binom");
1017 pos = total_cmd_end;
1018 }
1019 }
1020 // --- Square root ---
1021 "sqrt" => {
1022 let after = &input[total_cmd_end..];
1023 // Optional [n] root index, without its brackets.
1024 let (root_text, after_root) = match after
1025 .strip_prefix('[')
1026 .and_then(|after_lb| after_lb.find(']').map(|end| (after_lb, end)))
1027 {
1028 Some((after_lb, end)) => {
1029 (Some(&after_lb[..end]), total_cmd_end + end + 2)
1030 }
1031 None => (None, total_cmd_end),
1032 };
1033 if let Some(root) = root_text {
1034 append_superscript(&render_latex_to_string(root), &mut out);
1035 }
1036 out.push('\u{221a}');
1037 // One radical, and resume after the whole argument:
1038 // the old path pushed a second radical and re-read the
1039 // argument, and a radicand without braces never
1040 // advanced at all (U04-m2).
1041 if let Some((arg, after_arg)) = read_braced_at(input, after_root) {
1042 out.push_str(&format!("({})", render_latex_to_string(&arg)));
1043 pos = after_arg;
1044 } else {
1045 pos = after_root;
1046 }
1047 }
1048 // --- Sum, product, integral ---
1049 "sum" => {
1050 out.push('\u{2211}');
1051 pos = total_cmd_end;
1052 }
1053 "prod" => {
1054 out.push('\u{220f}');
1055 pos = total_cmd_end;
1056 }
1057 "int" => {
1058 out.push('\u{222b}');
1059 pos = total_cmd_end;
1060 }
1061 "iint" => {
1062 out.push('\u{222c}');
1063 pos = total_cmd_end;
1064 }
1065 "iiint" => {
1066 out.push('\u{222d}');
1067 pos = total_cmd_end;
1068 }
1069 "oint" => {
1070 out.push('\u{222e}');
1071 pos = total_cmd_end;
1072 }
1073 "oiint" => {
1074 out.push('\u{222f}');
1075 pos = total_cmd_end;
1076 }
1077 // --- Named operators ---
1078 "lim" => {
1079 out.push_str("lim");
1080 pos = total_cmd_end;
1081 }
1082 "sin" | "cos" | "tan" | "cot" | "sec" | "csc" | "log" | "ln" | "lg" | "exp"
1083 | "det" | "dim" | "ker" | "hom" | "max" | "min" | "sup" | "inf" | "arg"
1084 | "deg" | "mod" | "gcd" | "lcm" | "Pr" | "Var" | "Cov" | "Corr" | "tr"
1085 | "rank" | "Re" | "Im" | "sinh" | "cosh" | "tanh" | "coth" | "arcsin"
1086 | "arccos" | "arctan" => {
1087 out.push_str(cmd);
1088 pos = total_cmd_end;
1089 }
1090 // --- Arrows ---
1091 "to" | "rightarrow" => {
1092 out.push('\u{2192}');
1093 pos = total_cmd_end;
1094 }
1095 "leftarrow" => {
1096 out.push('\u{2190}');
1097 pos = total_cmd_end;
1098 }
1099 "Rightarrow" => {
1100 out.push('\u{21d2}');
1101 pos = total_cmd_end;
1102 }
1103 "Leftarrow" => {
1104 out.push('\u{21d0}');
1105 pos = total_cmd_end;
1106 }
1107 "Leftrightarrow" | "iff" => {
1108 out.push('\u{21d4}');
1109 pos = total_cmd_end;
1110 }
1111 "mapsto" => {
1112 out.push('\u{21a6}');
1113 pos = total_cmd_end;
1114 }
1115 "longrightarrow" => {
1116 out.push('\u{27f6}');
1117 pos = total_cmd_end;
1118 }
1119 "Longrightarrow" => {
1120 out.push('\u{27f9}');
1121 pos = total_cmd_end;
1122 }
1123 "uparrow" => {
1124 out.push('\u{2191}');
1125 pos = total_cmd_end;
1126 }
1127 "downarrow" => {
1128 out.push('\u{2193}');
1129 pos = total_cmd_end;
1130 }
1131 "Uparrow" => {
1132 out.push('\u{21d1}');
1133 pos = total_cmd_end;
1134 }
1135 "Downarrow" => {
1136 out.push('\u{21d3}');
1137 pos = total_cmd_end;
1138 }
1139 "longleftrightarrow" => {
1140 out.push('\u{27f7}');
1141 pos = total_cmd_end;
1142 }
1143 "Longleftrightarrow" => {
1144 out.push('\u{27fa}');
1145 pos = total_cmd_end;
1146 }
1147 "hookrightarrow" => {
1148 out.push('\u{21aa}');
1149 pos = total_cmd_end;
1150 }
1151 "hookleftarrow" => {
1152 out.push('\u{21a9}');
1153 pos = total_cmd_end;
1154 }
1155 "rightharpoonup" => {
1156 out.push('\u{21c0}');
1157 pos = total_cmd_end;
1158 }
1159 "rightharpoondown" => {
1160 out.push('\u{21c1}');
1161 pos = total_cmd_end;
1162 }
1163 "leftharpoonup" => {
1164 out.push('\u{21bc}');
1165 pos = total_cmd_end;
1166 }
1167 "leftharpoondown" => {
1168 out.push('\u{21bd}');
1169 pos = total_cmd_end;
1170 }
1171 "rightleftharpoons" => {
1172 out.push('\u{21cc}');
1173 pos = total_cmd_end;
1174 }
1175 "nrightarrow" => {
1176 out.push('\u{219b}');
1177 pos = total_cmd_end;
1178 }
1179 "nleftarrow" => {
1180 out.push('\u{219a}');
1181 pos = total_cmd_end;
1182 }
1183 // --- Unknown command ---
1184 _ => {
1185 if let Some(sym) = SYMBOLS.get_or_init(build_symbols).get(cmd) {
1186 out.push_str(sym);
1187 pos = total_cmd_end;
1188 // Check for braces after symbol (e.g., \alpha_{i})
1189 // The subscript/superscript will be handled by the
1190 // main loop as _ and ^
1191 } else {
1192 // --- Unknown command ---
1193 out.push('\\');
1194 out.push_str(cmd);
1195 pos = total_cmd_end;
1196 // If followed by {, include the braced argument
1197 if input[pos..].starts_with('{')
1198 && let Some((arg, new_pos)) = read_braced_at(input, pos)
1199 {
1200 out.push('{');
1201 out.push_str(&arg);
1202 out.push('}');
1203 pos = new_pos;
1204 }
1205 }
1206 }
1207 }
1208 }
1209 '_' => {
1210 // Read subscript
1211 let after = &input[pos + 1..];
1212 if after.starts_with('{') {
1213 if let Some((sub, new_pos)) = read_braced_at(input, pos + 1) {
1214 append_subscript(&render_latex_to_string(&sub), &mut out);
1215 pos = new_pos;
1216 } else {
1217 out.push('_');
1218 pos += 1;
1219 }
1220 } else {
1221 // Subscript with command like _\mu _\nu
1222 if let Some(after_bs) = after.strip_prefix('\\') {
1223 let cmd_end = after_bs
1224 .find(|c: char| !c.is_ascii_alphabetic())
1225 .unwrap_or(after_bs.len());
1226 let rendered = render_latex_to_string(&after[..1 + cmd_end]);
1227 append_subscript(&rendered, &mut out);
1228 pos += 1 + 1 + cmd_end;
1229 } else {
1230 let next = after.chars().next();
1231 if let Some(c) = next {
1232 append_subscript(&c.to_string(), &mut out);
1233 pos += 1 + c.len_utf8();
1234 } else {
1235 out.push('_');
1236 pos += 1;
1237 }
1238 }
1239 }
1240 }
1241 '^' => {
1242 // Read superscript
1243 let after = &input[pos + 1..];
1244 if after.starts_with('{') {
1245 if let Some((sup, new_pos)) = read_braced_at(input, pos + 1) {
1246 append_superscript(&render_latex_to_string(&sup), &mut out);
1247 pos = new_pos;
1248 } else {
1249 out.push('^');
1250 pos += 1;
1251 }
1252 } else {
1253 // Superscript with command like ^\dagger ^\rho
1254 if let Some(after_bs) = after.strip_prefix('\\') {
1255 let cmd_end = after_bs
1256 .find(|c: char| !c.is_ascii_alphabetic())
1257 .unwrap_or(after_bs.len());
1258 let rendered = render_latex_to_string(&after[..1 + cmd_end]);
1259 append_superscript(&rendered, &mut out);
1260 pos += 1 + 1 + cmd_end;
1261 } else {
1262 let next = after.chars().next();
1263 if let Some(c) = next {
1264 append_superscript(&c.to_string(), &mut out);
1265 pos += 1 + c.len_utf8();
1266 } else {
1267 out.push('^');
1268 pos += 1;
1269 }
1270 }
1271 }
1272 }
1273 '{' | '}' => {
1274 pos += ch_len;
1275 }
1276 ' ' => {
1277 if !out.ends_with(' ') {
1278 out.push(' ');
1279 }
1280 pos += ch_len;
1281 }
1282 '\n' => {
1283 if !out.ends_with(' ') {
1284 out.push(' ');
1285 }
1286 pos += ch_len;
1287 }
1288 // Punctuation that shouldn't be duplicated
1289 '~' => {
1290 // Non-breaking space
1291 out.push(' ');
1292 pos += ch_len;
1293 }
1294 _ => {
1295 out.push(ch);
1296 pos += ch_len;
1297 }
1298 }
1299 }
1300
1301 out.trim_end().to_string()
1302 }
1303
1304 /// Try to parse a `\begin{env_name}...\end{env_name}` block at the start of `input`.
1305 /// Returns (rendered_output, bytes_consumed) or None.
1306 fn try_render_env(input: &str) -> Option<(String, usize)> {
1307 let input_bytes = input.as_bytes();
1308
1309 // Check for \begin{
1310 if input.len() < 7 || &input_bytes[..7] != b"\\begin{" {
1311 return None;
1312 }
1313
1314 // Find closing }
1315 let close = input[7..].find('}')?;
1316 let env_name = &input[7..7 + close];
1317
1318 let content_start = 7 + close + 1; // after \begin{env_name}
1319 if content_start >= input.len() {
1320 return None;
1321 }
1322
1323 // Find matching \end{env_name}
1324 let end_tag = format!("\\end{{{env_name}}}");
1325 let rest = &input[content_start..];
1326
1327 // Simple depth tracking for nested braces
1328 let mut depth = 0i32;
1329 let mut search_pos = 0;
1330
1331 while search_pos < rest.len() {
1332 let remaining_search = &rest[search_pos..];
1333
1334 if remaining_search.starts_with(&end_tag) && depth == 0 {
1335 let env_content = &rest[..search_pos];
1336 let rendered = render_environment(env_name, env_content);
1337 let consumed = content_start + search_pos + end_tag.len();
1338 // --- Spacing ---
1339 return Some((rendered, consumed));
1340 }
1341
1342 match remaining_search.as_bytes().first()? {
1343 b'{' => depth += 1,
1344 b'}' => depth -= 1,
1345 _ => {}
1346 }
1347 search_pos += remaining_search.chars().next().map_or(1, char::len_utf8);
1348 }
1349
1350 None
1351 }
1352
1353 // --- Superscript / Subscript ---
1354
1355 fn append_superscript(s: &str, out: &mut String) {
1356 for c in s.chars() {
1357 out.push(match c {
1358 '0' => '\u{2070}',
1359 '1' => '\u{00b9}',
1360 '2' => '\u{00b2}',
1361 '3' => '\u{00b3}',
1362 '4' => '\u{2074}',
1363 '5' => '\u{2075}',
1364 '6' => '\u{2076}',
1365 '7' => '\u{2077}',
1366 '8' => '\u{2078}',
1367 '9' => '\u{2079}',
1368 '+' => '\u{207a}',
1369 '-' => '\u{207b}',
1370 '=' => '\u{207c}',
1371 '(' => '\u{207d}',
1372 ')' => '\u{207e}',
1373 'n' => '\u{207f}',
1374 'i' => '\u{2071}',
1375 'a' => '\u{1d43}',
1376 'b' => '\u{1d47}',
1377 'c' => '\u{1d9c}',
1378 'd' => '\u{1d48}',
1379 'e' => '\u{1d49}',
1380 'f' => '\u{1da0}',
1381 'g' => '\u{1d4d}',
1382 'h' => '\u{02b0}',
1383 'j' => '\u{02b2}',
1384 'k' => '\u{1d4f}',
1385 'l' => '\u{02e1}',
1386 'm' => '\u{1d50}',
1387 'o' => '\u{1d52}',
1388 'p' => '\u{1d56}',
1389 'r' => '\u{02b3}',
1390 's' => '\u{02e2}',
1391 't' => '\u{1d57}',
1392 'u' => '\u{1d58}',
1393 'v' => '\u{1d5b}',
1394 'w' => '\u{02b7}',
1395 'x' => '\u{02e3}',
1396 'y' => '\u{02b8}',
1397 'z' => '\u{1dbb}',
1398 _ => c,
1399 });
1400 }
1401 }
1402
1403 fn append_subscript(s: &str, out: &mut String) {
1404 for c in s.chars() {
1405 out.push(match c {
1406 '0' => '\u{2080}',
1407 '1' => '\u{2081}',
1408 '2' => '\u{2082}',
1409 '3' => '\u{2083}',
1410 '4' => '\u{2084}',
1411 '5' => '\u{2085}',
1412 '6' => '\u{2086}',
1413 '7' => '\u{2087}',
1414 '8' => '\u{2088}',
1415 '9' => '\u{2089}',
1416 '+' => '\u{208a}',
1417 '-' => '\u{208b}',
1418 '=' => '\u{208c}',
1419 'a' => '\u{2090}',
1420 'e' => '\u{2091}',
1421 'h' => '\u{2095}',
1422 'i' => '\u{1d62}',
1423 'k' => '\u{2096}',
1424 'l' => '\u{2097}',
1425 'm' => '\u{2098}',
1426 'n' => '\u{2099}',
1427 'o' => '\u{2092}',
1428 'p' => '\u{209a}',
1429 'r' => '\u{1d63}',
1430 's' => '\u{209b}',
1431 't' => '\u{209c}',
1432 'u' => '\u{1d64}',
1433 'v' => '\u{1d65}',
1434 'x' => '\u{2093}',
1435 _ => c,
1436 });
1437 }
1438 }
1439
1440 // --- Symbol table ---
1441
1442 type SymbolMap = HashMap<&'static str, &'static str>;
1443 fn build_symbols() -> SymbolMap {
1444 let mut m = SymbolMap::new();
1445 // Lowercase Greek
1446 for (k, v) in [
1447 ("alpha", "\u{03b1}"),
1448 ("beta", "\u{03b2}"),
1449 ("gamma", "\u{03b3}"),
1450 ("delta", "\u{03b4}"),
1451 ("epsilon", "\u{03b5}"),
1452 ("zeta", "\u{03b6}"),
1453 ("eta", "\u{03b7}"),
1454 ("theta", "\u{03b8}"),
1455 ("iota", "\u{03b9}"),
1456 ("kappa", "\u{03ba}"),
1457 ("lambda", "\u{03bb}"),
1458 ("mu", "\u{03bc}"),
1459 ("nu", "\u{03bd}"),
1460 ("xi", "\u{03be}"),
1461 ("pi", "\u{03c0}"),
1462 ("rho", "\u{03c1}"),
1463 ("sigma", "\u{03c3}"),
1464 ("tau", "\u{03c4}"),
1465 ("upsilon", "\u{03c5}"),
1466 ("phi", "\u{03c6}"),
1467 ("chi", "\u{03c7}"),
1468 ("psi", "\u{03c8}"),
1469 ("omega", "\u{03c9}"),
1470 ("varepsilon", "\u{03b5}"),
1471 ("vartheta", "\u{03d1}"),
1472 ("varphi", "\u{03c6}"),
1473 ("varrho", "\u{03f1}"),
1474 ] {
1475 m.insert(k, v);
1476 }
1477 // Uppercase Greek
1478 for (k, v) in [
1479 ("Gamma", "\u{0393}"),
1480 ("Delta", "\u{0394}"),
1481 ("Theta", "\u{0398}"),
1482 ("Lambda", "\u{039b}"),
1483 ("Xi", "\u{039e}"),
1484 ("Pi", "\u{03a0}"),
1485 ("Sigma", "\u{03a3}"),
1486 ("Upsilon", "\u{03a5}"),
1487 ("Phi", "\u{03a6}"),
1488 ("Psi", "\u{03a8}"),
1489 ("Omega", "\u{03a9}"),
1490 ] {
1491 m.insert(k, v);
1492 }
1493 // Miscellaneous
1494 for (k, v) in [
1495 ("infty", "\u{221e}"),
1496 ("partial", "\u{2202}"),
1497 ("nabla", "\u{2207}"),
1498 ("ell", "\u{2113}"),
1499 ("hbar", "\u{210f}"),
1500 ("Im", "\u{2111}"),
1501 ("Re", "\u{211c}"),
1502 ("emptyset", "\u{2205}"),
1503 ("varnothing", "\u{2205}"),
1504 ("aleph", "\u{2135}"),
1505 ("angle", "\u{2220}"),
1506 ("measuredangle", "\u{2221}"),
1507 ("langle", "\u{27e8}"),
1508 ("rangle", "\u{27e9}"),
1509 ("perp", "\u{22a5}"),
1510 ("parallel", "\u{2225}"),
1511 ("nparallel", "\u{2226}"),
1512 ("prime", "\u{2032}"),
1513 ("surd", "\u{221a}"),
1514 ("top", "\u{22a4}"),
1515 ("bot", "\u{22a5}"),
1516 ("imath", "\u{0131}"),
1517 ("jmath", "\u{0237}"),
1518 ("wp", "\u{2118}"),
1519 ("clubsuit", "\u{2663}"),
1520 ("diamondsuit", "\u{2662}"),
1521 ("heartsuit", "\u{2661}"),
1522 ("spadesuit", "\u{2660}"),
1523 ("triangle", "\u{25b3}"),
1524 ("Box", "\u{25a1}"),
1525 ("Diamond", "\u{25c7}"),
1526 ("flat", "\u{266d}"),
1527 ("natural", "\u{266e}"),
1528 ("sharp", "\u{266f}"),
1529 ("colon", ":"),
1530 ("backslash", "\\"),
1531 ] {
1532 m.insert(k, v);
1533 }
1534 // Set / relation symbols
1535 for (k, v) in [
1536 ("in", "\u{2208}"),
1537 ("notin", "\u{2209}"),
1538 ("ni", "\u{220b}"),
1539 ("subset", "\u{2282}"),
1540 ("supset", "\u{2283}"),
1541 ("subseteq", "\u{2286}"),
1542 ("supseteq", "\u{2287}"),
1543 ("subsetneq", "\u{228a}"),
1544 ("supsetneq", "\u{228b}"),
1545 ("cup", "\u{222a}"),
1546 ("bigcup", "\u{22c3}"),
1547 ("cap", "\u{2229}"),
1548 ("bigcap", "\u{22c2}"),
1549 ("vee", "\u{2228}"),
1550 ("wedge", "\u{2227}"),
1551 ("oplus", "\u{2295}"),
1552 ("ominus", "\u{2296}"),
1553 ("otimes", "\u{2297}"),
1554 ("oslash", "\u{2298}"),
1555 ("odot", "\u{2299}"),
1556 ("sqcap", "\u{2293}"),
1557 ("sqcup", "\u{2294}"),
1558 ("uplus", "\u{228e}"),
1559 ("amalg", "\u{2a3f}"),
1560 ("forall", "\u{2200}"),
1561 ("exists", "\u{2203}"),
1562 ("nexists", "\u{2204}"),
1563 ("neg", "\u{00ac}"),
1564 ("lnot", "\u{00ac}"),
1565 ("land", "\u{2227}"),
1566 ("lor", "\u{2228}"),
1567 ("implies", "\u{21d2}"),
1568 ("iff", "\u{21d4}"),
1569 ("gets", "\u{2190}"),
1570 ("sim", "\u{223c}"),
1571 ("nsim", "\u{2241}"),
1572 ("simeq", "\u{2243}"),
1573 ("nsimeq", "\u{2244}"),
1574 ("cong", "\u{2245}"),
1575 ("ncong", "\u{2247}"),
1576 ("approx", "\u{2248}"),
1577 ("napprox", "\u{2249}"),
1578 ("neq", "\u{2260}"),
1579 ("ne", "\u{2260}"),
1580 ("equiv", "\u{2261}"),
1581 ("nequiv", "\u{2262}"),
1582 ("le", "\u{2264}"),
1583 ("ge", "\u{2265}"),
1584 ("leq", "\u{2264}"),
1585 ("geq", "\u{2265}"),
1586 ("leqq", "\u{2266}"),
1587 ("geqq", "\u{2267}"),
1588 ("lneq", "\u{2268}"),
1589 ("gneq", "\u{2269}"),
1590 ("ll", "\u{226a}"),
1591 ("gg", "\u{226b}"),
1592 ("lll", "\u{22d8}"),
1593 ("ggg", "\u{22d9}"),
1594 ("prec", "\u{227a}"),
1595 ("succ", "\u{227b}"),
1596 ("preceq", "\u{227c}"),
1597 ("succeq", "\u{227d}"),
1598 ("preccurlyeq", "\u{227c}"),
1599 ("succcurlyeq", "\u{227d}"),
1600 ("propto", "\u{221d}"),
1601 ("models", "\u{22a7}"),
1602 ("dashv", "\u{22a3}"),
1603 ("vdash", "\u{22a2}"),
1604 ("mid", "|"),
1605 ("nmid", "\u{2224}"),
1606 ] {
1607 m.insert(k, v);
1608 }
1609 // Operators
1610 for (k, v) in [
1611 ("times", "\u{00d7}"),
1612 ("div", "\u{00f7}"),
1613 ("pm", "\u{00b1}"),
1614 ("mp", "\u{2213}"),
1615 ("cdot", "\u{00b7}"),
1616 ("ast", "\u{2217}"),
1617 ("circ", "\u{2218}"),
1618 ("bullet", "\u{2022}"),
1619 ("setminus", "\u{2216}"),
1620 ("smallsetminus", "\u{2216}"),
1621 ("wr", "\u{2240}"),
1622 ("dagger", "\u{2020}"),
1623 ("ddagger", "\u{2021}"),
1624 ("star", "\u{22c6}"),
1625 ("diamond", "\u{22c4}"),
1626 ] {
1627 m.insert(k, v);
1628 }
1629 // Dots
1630 for (k, v) in [
1631 ("cdots", "\u{2026}"),
1632 ("ldots", "\u{2026}"),
1633 ("vdots", "\u{22ee}"),
1634 ("ddots", "\u{22f1}"),
1635 ("idots", "\u{2026}"),
1636 ] {
1637 m.insert(k, v);
1638 }
1639 // Named functions not covered by the inline list
1640 for (k, v) in [
1641 ("arccos", "arccos"),
1642 ("arcsin", "arcsin"),
1643 ("arctan", "arctan"),
1644 ("arg", "arg"),
1645 ("cos", "cos"),
1646 ("cosh", "cosh"),
1647 ("cot", "cot"),
1648 ("coth", "coth"),
1649 ("csc", "csc"),
1650 ("deg", "deg"),
1651 ("det", "det"),
1652 ("dim", "dim"),
1653 ("exp", "exp"),
1654 ("gcd", "gcd"),
1655 ("hom", "hom"),
1656 ("inf", "inf"),
1657 ("ker", "ker"),
1658 ("lg", "lg"),
1659 ("lim", "lim"),
1660 ("liminf", "liminf"),
1661 ("limsup", "limsup"),
1662 ("ln", "ln"),
1663 ("log", "log"),
1664 ("max", "max"),
1665 ("min", "min"),
1666 ("mod", "mod"),
1667 ("sec", "sec"),
1668 ("sin", "sin"),
1669 ("sinh", "sinh"),
1670 ("sup", "sup"),
1671 ("tan", "tan"),
1672 ("tanh", "tanh"),
1673 ] {
1674 m.insert(k, v);
1675 }
1676 m
1677 }
1678
1679 static SYMBOLS: OnceLock<SymbolMap> = OnceLock::new();
1680
1681 #[cfg(test)]
1682 mod tests {
1683 use super::*;
1684
1685 #[test]
1686 fn test_superscript() {
1687 assert_eq!(render_latex_to_string("x^2"), "x\u{00b2}");
1688 }
1689 /// U04-m2: one radical, the index as a superscript, and rendering
1690 /// resumes after the argument instead of printing it twice.
1691 #[test]
1692 fn sqrt_renders_one_radical_and_consumes_its_argument() {
1693 assert_eq!(render_latex_to_string(r"\sqrt{x}+1"), "\u{221a}(x)+1");
1694 assert_eq!(
1695 render_latex_to_string(r"\sqrt[3]{x}"),
1696 "\u{00b3}\u{221a}(x)"
1697 );
1698 }
1699
1700 /// A radicand or binomial without braces must still finish rendering;
1701 /// the old branches never advanced and spun the render loop forever.
1702 #[test]
1703 fn malformed_sqrt_and_binom_terminate() {
1704 let (tx, rx) = std::sync::mpsc::channel();
1705 std::thread::spawn(move || {
1706 let _ = tx.send((
1707 render_latex_to_string(r"\sqrt 2"),
1708 render_latex_to_string(r"\binom{n} k"),
1709 ));
1710 });
1711 let (sqrt, binom) = rx
1712 .recv_timeout(std::time::Duration::from_secs(5))
1713 .expect("latex rendering must terminate");
1714 assert!(sqrt.starts_with('\u{221a}'), "{sqrt}");
1715 assert!(sqrt.ends_with('2'), "{sqrt}");
1716 assert!(binom.contains("binom"), "{binom}");
1717 }
1718
1719 #[test]
1720 fn test_subscript() {
1721 assert_eq!(render_latex_to_string("x_1"), "x\u{2081}");
1722 }
1723 #[test]
1724 fn test_blackboard() {
1725 assert_eq!(render_latex_to_string(r"\mathbb{R}"), "\u{211d}");
1726 }
1727 #[test]
1728 fn test_infty() {
1729 assert_eq!(render_latex_to_string(r"\infty"), "\u{221e}");
1730 }
1731 #[test]
1732 fn test_inline_dollar() {
1733 let r = render_latex_in_text(r"text $x^2$ more");
1734 assert_eq!(r, "text x\u{00b2} more");
1735 assert!(matches!(r, std::borrow::Cow::Owned(_)));
1736 }
1737 #[test]
1738 fn test_display_bracket() {
1739 let r = render_latex_in_text(r"text \[x^2\] more");
1740 assert_eq!(r, "text x\u{00b2} more");
1741 }
1742 #[test]
1743 fn no_math_is_borrowed_without_copy() {
1744 let r = render_latex_in_text("plain prose with `code` but no math at all");
1745 assert!(matches!(r, std::borrow::Cow::Borrowed(_)));
1746 assert_eq!(&*r, "plain prose with `code` but no math at all");
1747 // The '$' fast path must not miss \(
1748 let p = render_latex_in_text("parens \\(x^2\\) inline");
1749 assert!(matches!(p, std::borrow::Cow::Owned(_)));
1750 assert_eq!(&*p, "parens x\u{00b2} inline");
1751 }
1752 #[test]
1753 fn preserves_currency() {
1754 assert_eq!(render_latex_in_text("cost $5 and $10"), "cost $5 and $10");
1755 }
1756 #[test]
1757 fn preserves_markdown_code() {
1758 assert_eq!(
1759 render_latex_in_text("`$x^2$` and $y^2$"),
1760 "`$x^2$` and y\u{00b2}"
1761 );
1762 assert_eq!(
1763 render_latex_in_text("```sh\necho $HOME\n```"),
1764 "```sh\necho $HOME\n```"
1765 );
1766 }
1767 #[test]
1768 fn preserves_escaped_dollars_and_unknown_commands() {
1769 assert_eq!(
1770 render_latex_in_text(r"cost \$5 and $\operatorname{foo}$"),
1771 r"cost \$5 and foo"
1772 );
1773 }
1774 #[test]
1775 fn test_text() {
1776 assert_eq!(render_latex_to_string(r"\text{hello}"), "hello");
1777 }
1778 #[test]
1779 fn test_operatorname() {
1780 assert_eq!(render_latex_to_string(r"\operatorname{sgn}"), "sgn");
1781 }
1782 #[test]
1783 fn test_left_right() {
1784 assert_eq!(
1785 render_latex_to_string(r"\left(\frac{a}{b}\right)"),
1786 "((a/b))"
1787 );
1788 }
1789 #[test]
1790 fn test_mathbf() {
1791 assert_eq!(render_latex_to_string(r"\mathbf{E}"), "E");
1792 }
1793 #[test]
1794 fn test_quad() {
1795 assert_eq!(render_latex_to_string(r"a \quad b"), "a b");
1796 }
1797 #[test]
1798 fn test_environment_aligned() {
1799 let input = r"\begin{aligned} x &= y \\ a &= b \end{aligned}";
1800 let result = render_latex_to_string(input);
1801 assert!(result.contains("x"));
1802 assert!(result.contains("y"));
1803 assert!(result.contains("a"));
1804 assert!(result.contains("b"));
1805 }
1806 #[test]
1807 fn test_environment_matrix() {
1808 let input = r"\begin{pmatrix} a & b \\ c & d \end{pmatrix}";
1809 let result = render_latex_to_string(input);
1810 assert!(result.contains("a"));
1811 assert!(result.contains("b"));
1812 assert!(result.contains("c"));
1813 assert!(result.contains("d"));
1814 }
1815 #[test]
1816 fn test_environment_cases() {
1817 let input = r"\begin{cases} x^2 & x < 0 \\ 0 & x = 0 \\ \ln x & x > 0 \end{cases}";
1818 let result = render_latex_to_string(input);
1819 assert!(result.contains("x\u{00b2}"));
1820 assert!(result.contains("ln"));
1821 }
1822 }
1823
1823 lines RUST