gleplot 6.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gleplot/mathtext.py ADDED
@@ -0,0 +1,679 @@
1
+ """Translate matplotlib-style ``$...$`` mathtext into GLE's native text markup.
2
+
3
+ Matplotlib users write axis labels, titles and legend keys such as
4
+ ``r"$\\chi$ (emu/mol)"`` or ``r"emu mol$^{-1}$"``. GLE's text engine speaks a
5
+ TeX-like markup of its own that natively understands LaTeX symbol macros
6
+ (``\\alpha`` ... ``\\Omega``, ``\\chi``, ``\\times`` ...), braced sub/superscripts
7
+ (``^{}`` / ``_{}``) and a handful of spacing/font commands. This module bridges
8
+ the two so matplotlib users get Greek/math rendering without learning GLE
9
+ markup.
10
+
11
+ Design (see the feature brief / CLAUDE.md conventions):
12
+
13
+ * **Translate at STORE time**, exactly like the colour/marker mappings: the
14
+ object model stores the *translated* GLE-markup string and the writer stays
15
+ untouched. A ``.gle`` file re-parsed by the recognizer already contains GLE
16
+ markup, so writer -> recognizer -> writer stays a byte-identical fixed point.
17
+ * **Idempotent.** ``translate(translate(s)) == translate(s)``: everything the
18
+ translator emits (GLE macros and brace groups belonging to them) is copied
19
+ verbatim on a second pass, so a stored label can be re-translated safely --
20
+ an editor built on gleplot does exactly that on every edit.
21
+ * **Graceful degradation.** An odd number of unescaped ``$`` (which matplotlib
22
+ would reject) leaves the string completely unchanged rather than guessing.
23
+ * **Literal by default, math by opt-in** -- matplotlib's own contract. Text
24
+ *inside* ``$...$`` is translated as math; text outside is escaped by
25
+ :func:`escape_gle_text` so it renders literally, because GLE's TeX-ish text
26
+ mode would otherwise read ``lambda_tail`` as a subscript and swallow braces.
27
+ A **backslash still opens GLE markup** outside math (``\\degree``,
28
+ ``{\\bf x}``): that is the escape hatch for GLE's own text commands, and it
29
+ is what keeps labels recovered from a ``.gle`` file rendering as written.
30
+
31
+ ``\\$`` is a literal dollar sign everywhere and never opens/closes a math
32
+ segment.
33
+
34
+ The supported-macro tables below are derived from the GLE 4.3.10 manual:
35
+
36
+ * LaTeX symbol macros (Greek etc.): ``appendix/fig/symbols.csv`` /
37
+ ``appendix/sym.tex`` ("LaTeX Symbols").
38
+ * Text commands (``^{}`` ``_{}`` ``\\,`` ``\\:`` ``\\;`` ``\\!`` ``\\_`` ``{\\rm}``
39
+ ``{\\it}`` ``{\\bf}`` ``{\\tt}``): ``appendix/sym.tex`` ("LaTeX Macros") and
40
+ ``primitives/cmds.tex`` (the ``text`` primitive).
41
+
42
+ Examples
43
+ --------
44
+ >>> mathtext_to_gle(r"$\\chi$ (emu/mol)")
45
+ '\\\\chi{} (emu/mol)'
46
+ >>> mathtext_to_gle(r"emu mol$^{-1}$")
47
+ 'emu mol^{-1}'
48
+ >>> mathtext_to_gle(r"$x_i^2$")
49
+ 'x_{i}^{2}'
50
+ >>> mathtext_to_gle(r"$T$ (\\degree C)") # already GLE markup outside math
51
+ 'T (\\\\degree C)'
52
+ >>> mathtext_to_gle(r"cost \\$5") # escaped dollar -> literal
53
+ 'cost $5'
54
+ >>> mathtext_to_gle(r"$x = 5") # unmatched $ -> unchanged
55
+ '$x = 5'
56
+ >>> mathtext_to_gle(r"\\chi{} (emu/mol)") # GLE markup -> identity
57
+ '\\\\chi{} (emu/mol)'
58
+ >>> mathtext_to_gle("lambda_tail") # plain text -> literal
59
+ 'lambda\\\\_tail'
60
+ """
61
+
62
+ import re
63
+ from typing import List, Optional, Tuple, overload
64
+
65
+ __all__ = ["mathtext_to_gle", "escape_gle_text"]
66
+
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # Supported-macro tables (provenance: GLE 4.3.10 manual)
70
+ # ---------------------------------------------------------------------------
71
+
72
+ # LaTeX symbol macros GLE renders natively -> passed through verbatim as
73
+ # ``\name``. Verbatim copy of the manual's symbol table
74
+ # (gle-manual/appendix/fig/symbols.csv, rendered by appendix/sym.tex).
75
+ # Includes Greek letters plus the common math symbols matplotlib users reach
76
+ # for (\times, \cdot, \pm, \infty, \degree, \circ, \approx, \leq, \geq ...).
77
+ GLE_SYMBOL_MACROS = frozenset(
78
+ {
79
+ "AA",
80
+ "AE",
81
+ "Delta",
82
+ "Downarrow",
83
+ "Gamma",
84
+ "Im",
85
+ "L",
86
+ "Lambda",
87
+ "Leftarrow",
88
+ "Leftrightarrow",
89
+ "O",
90
+ "OE",
91
+ "Omega",
92
+ "P",
93
+ "Phi",
94
+ "Pi",
95
+ "Psi",
96
+ "Re",
97
+ "Rightarrow",
98
+ "S",
99
+ "Sigma",
100
+ "Theta",
101
+ "Uparrow",
102
+ "Updownarrow",
103
+ "Upsilon",
104
+ "Xi",
105
+ "aa",
106
+ "ae",
107
+ "aleph",
108
+ "alpha",
109
+ "amalg",
110
+ "approx",
111
+ "ast",
112
+ "asymp",
113
+ "backslash",
114
+ "beta",
115
+ "bigcap",
116
+ "bigcirc",
117
+ "bigcup",
118
+ "bigodot",
119
+ "bigoplus",
120
+ "bigotimes",
121
+ "bigsqcup",
122
+ "bigtriangledown",
123
+ "bigtriangleup",
124
+ "biguplus",
125
+ "bigvee",
126
+ "bigwedge",
127
+ "bot",
128
+ "bullet",
129
+ "cap",
130
+ "cdot",
131
+ "chi",
132
+ "circ",
133
+ "clubsuit",
134
+ "coprod",
135
+ "cup",
136
+ "dag",
137
+ "dagger",
138
+ "dashv",
139
+ "ddag",
140
+ "ddagger",
141
+ "degree",
142
+ "delta",
143
+ "diamond",
144
+ "diamondsuit",
145
+ "div",
146
+ "downarrow",
147
+ "ell",
148
+ "emptyset",
149
+ "epsilon",
150
+ "equiv",
151
+ "eta",
152
+ "exists",
153
+ "flat",
154
+ "forall",
155
+ "frown",
156
+ "gamma",
157
+ "geq",
158
+ "gg",
159
+ "heartsuit",
160
+ "i",
161
+ "imath",
162
+ "in",
163
+ "infty",
164
+ "intop",
165
+ "iota",
166
+ "j",
167
+ "jmath",
168
+ "kappa",
169
+ "l",
170
+ "lambda",
171
+ "land",
172
+ "leftarrow",
173
+ "leftharpoondown",
174
+ "leftharpoonup",
175
+ "leftrightarrow",
176
+ "leq",
177
+ "lhook",
178
+ "ll",
179
+ "lor",
180
+ "mapsto",
181
+ "mapstochar",
182
+ "mid",
183
+ "minus",
184
+ "mp",
185
+ "mu",
186
+ "nabla",
187
+ "natural",
188
+ "nearrow",
189
+ "neg",
190
+ "neq",
191
+ "ni",
192
+ "not",
193
+ "nu",
194
+ "nwarrow",
195
+ "o",
196
+ "odot",
197
+ "oe",
198
+ "ointop",
199
+ "omega",
200
+ "ominus",
201
+ "oplus",
202
+ "oslash",
203
+ "otimes",
204
+ "owns",
205
+ "parallel",
206
+ "partial",
207
+ "perp",
208
+ "phi",
209
+ "pi",
210
+ "pm",
211
+ "prec",
212
+ "preceq",
213
+ "prime",
214
+ "prod",
215
+ "propto",
216
+ "psi",
217
+ "rho",
218
+ "rhook",
219
+ "rightarrow",
220
+ "rightharpoondown",
221
+ "rightharpoonup",
222
+ "searrow",
223
+ "setminus",
224
+ "sharp",
225
+ "sigma",
226
+ "sim",
227
+ "simeq",
228
+ "smallint",
229
+ "smile",
230
+ "spadesuit",
231
+ "sqcap",
232
+ "sqcup",
233
+ "sqsubseteq",
234
+ "sqsupseteq",
235
+ "ss",
236
+ "star",
237
+ "subset",
238
+ "subseteq",
239
+ "succ",
240
+ "succeq",
241
+ "sum",
242
+ "supset",
243
+ "supseteq",
244
+ "swarrow",
245
+ "tau",
246
+ "theta",
247
+ "times",
248
+ "top",
249
+ "triangle",
250
+ "triangleleft",
251
+ "triangleright",
252
+ "uparrow",
253
+ "updownarrow",
254
+ "uplus",
255
+ "upsilon",
256
+ "varepsilon",
257
+ "varphi",
258
+ "varpi",
259
+ "varrho",
260
+ "varsigma",
261
+ "vartheta",
262
+ "vdash",
263
+ "vee",
264
+ "wedge",
265
+ "wp",
266
+ "wr",
267
+ "xi",
268
+ "zeta",
269
+ }
270
+ )
271
+
272
+ # ``\mathXX{...}`` / ``\textXX{...}`` font macros -> GLE inline font groups
273
+ # ``{\rm ...}`` / ``{\it ...}`` / ``{\bf ...}`` / ``{\tt ...}``
274
+ # (gle-manual/appendix/sym.tex "LaTeX Macros"; primitives/cmds.tex text cmds).
275
+ # matplotlib's default math font is italic, so ``\mathrm``/``\text`` force
276
+ # upright roman. Families GLE has no simple inline equivalent for (sans-serif)
277
+ # degrade to their contents (braces stripped) to preserve the text.
278
+ FONT_MACROS = {
279
+ "mathrm": "rm",
280
+ "mathit": "it",
281
+ "mathbf": "bf",
282
+ "mathtt": "tt",
283
+ "text": "rm",
284
+ "textrm": "rm",
285
+ "textit": "it",
286
+ "textbf": "bf",
287
+ "texttt": "tt",
288
+ "mathsf": None, # no inline sans-serif in GLE -> strip to contents
289
+ "mathcal": None, # no calligraphic font -> strip to contents
290
+ "mathbb": None, # no blackboard-bold font -> strip to contents
291
+ "operatorname": "rm",
292
+ }
293
+
294
+ # Backslash + single non-letter symbol macros handled explicitly inside math.
295
+ # GLE natively supports the spacing macros ``\, \: \; \!`` and the literal
296
+ # underscore ``\_`` (appendix/sym.tex). Others map to the bare character.
297
+ _SYMBOL_ESCAPES = {
298
+ ",": "\\,", # thin space (GLE: 0.5em)
299
+ ":": "\\:", # medium space (GLE: 1em)
300
+ ";": "\\;", # thick space (GLE: 2em)
301
+ "!": "\\!", # negative thin space (GLE: -0.5em)
302
+ " ": "\\,", # LaTeX control space -> thin space
303
+ "_": "\\_", # literal underscore (GLE native escape)
304
+ "%": "%",
305
+ "&": "&",
306
+ "#": "#",
307
+ "{": "\\char{123}", # a bare brace is grouping in GLE and disappears
308
+ "}": "\\char{125}",
309
+ "$": "$",
310
+ }
311
+
312
+ # ---------------------------------------------------------------------------
313
+ # Text-mode escaping
314
+ # ---------------------------------------------------------------------------
315
+ #
316
+ # GLE's text engine is TeX-ish everywhere, not only inside math: ``_`` and
317
+ # ``^`` start a subscript/superscript and braces group silently. matplotlib
318
+ # renders a plain string literally and takes math only inside ``$...$``, so
319
+ # gleplot escapes those characters in every non-math segment.
320
+ #
321
+ # The escapes are the ones GLE actually renders (verified against GLE 4.3.10
322
+ # with its standard PostScript fonts): ``\_`` is the manual's "underscore
323
+ # character", while ``\^`` and ``\{`` are *accents*, not literals -- the
324
+ # literal caret and braces have to come from ``\char{n}`` (manual appendix
325
+ # A.3, "Any character in current font").
326
+ TEXT_ESCAPES = {
327
+ "_": "\\_",
328
+ "^": "\\char{94}",
329
+ "{": "\\char{123}",
330
+ "}": "\\char{125}",
331
+ }
332
+
333
+ # A GLE token that ends in a bare macro name (``\word``). Used to decide whether
334
+ # a math->text boundary needs a ``{}`` terminator so GLE does not swallow the
335
+ # following space or merge the macro with following letters.
336
+ _TRAILING_MACRO = re.compile(r"\\[A-Za-z]+$")
337
+
338
+
339
+ @overload
340
+ def mathtext_to_gle(s: str) -> str: ...
341
+
342
+
343
+ @overload
344
+ def mathtext_to_gle(s: None) -> None: ...
345
+
346
+
347
+ def mathtext_to_gle(s: Optional[str]) -> Optional[str]:
348
+ """Translate matplotlib mathtext (``$...$``) in *s* into GLE text markup.
349
+
350
+ Parameters
351
+ ----------
352
+ s : str or None
353
+ A display string as a matplotlib user would write it. Non-strings
354
+ (including ``None``) are returned unchanged, so callers may pass an
355
+ optional label straight through.
356
+
357
+ Returns
358
+ -------
359
+ str or None
360
+ The string with every ``$...$`` math segment rewritten in GLE markup
361
+ and every non-math segment escaped so it renders literally (see
362
+ :func:`escape_gle_text`). Returned unchanged when the unescaped ``$``
363
+ count is odd (matplotlib would error; we degrade gracefully rather
364
+ than guess what was meant).
365
+ """
366
+ if not isinstance(s, str):
367
+ return s
368
+ if "$" not in s:
369
+ return escape_gle_text(s)
370
+
371
+ segments = _split_segments(s)
372
+ if segments is None:
373
+ # Unbalanced ``$`` -> leave the caller's string exactly as given.
374
+ return s
375
+
376
+ # Translate each segment, then stitch, inserting ``{}`` after a math
377
+ # segment that ends in a bare macro when the *next emitted character*
378
+ # (across any following segments) is a letter or whitespace.
379
+ rendered: List[Tuple[str, bool]] = []
380
+ for kind, text in segments:
381
+ if kind == "math":
382
+ gle = _translate_math(text)
383
+ rendered.append((gle, bool(_TRAILING_MACRO.search(gle))))
384
+ else:
385
+ rendered.append((escape_gle_text(text), False))
386
+
387
+ out: List[str] = []
388
+ for idx, (text, trailing_macro) in enumerate(rendered):
389
+ out.append(text)
390
+ if trailing_macro:
391
+ nxt = _next_char(rendered, idx + 1)
392
+ if nxt is not None and (nxt.isalpha() or nxt.isspace()):
393
+ out.append("{}")
394
+ return "".join(out)
395
+
396
+
397
+ def escape_gle_text(s: str) -> str:
398
+ """Escape a non-math string so GLE renders it literally.
399
+
400
+ GLE's text engine reads ``_``/``^`` as subscript/superscript and ``{}``
401
+ as silent grouping, so a plain label like ``lambda_tail`` renders as
402
+ "lambda" with a subscripted "tail" and ``set {a, b}`` loses its braces.
403
+ matplotlib renders plain strings literally, so gleplot does too: these
404
+ four characters are escaped everywhere outside ``$...$``.
405
+
406
+ A **backslash still opens GLE markup** -- that is gleplot's opt-in to
407
+ GLE's own text commands outside math mode, and it is what keeps
408
+ round-tripped ``.gle`` labels (``\\chi{} (emu/mol)``, ``{\\bf bold}``)
409
+ rendering as they were written. So this function copies verbatim:
410
+
411
+ * a macro token ``\\name`` (or ``\\`` + one non-letter) and any brace
412
+ group that directly follows it -- ``\\char{95}``, ``\\rule{2}{4}``;
413
+ * a brace group whose contents start with a macro -- ``{\\bf bold}``;
414
+ * a *braced* script, ``_{...}`` or ``^{...}`` -- the form the math
415
+ translator emits and the documented GLE markup spelling of a
416
+ sub/superscript. Only a bare ``_``/``^`` is escaped, which is exactly
417
+ the accident that mangles ``lambda_tail``.
418
+
419
+ Everything else is literal text. The two rules above are also what makes
420
+ the escaping **idempotent**: the escapes it emits (``\\_``,
421
+ ``\\char{94}``) are themselves macro tokens, so escaping twice is
422
+ escaping once, and a stored label can be re-translated safely (an editor
423
+ built on gleplot does exactly that on every edit).
424
+
425
+ Parameters
426
+ ----------
427
+ s : str
428
+ A non-math display string.
429
+
430
+ Returns
431
+ -------
432
+ str
433
+ The same text with GLE's special characters escaped.
434
+
435
+ Examples
436
+ --------
437
+ >>> escape_gle_text("lambda_tail")
438
+ 'lambda\\\\_tail'
439
+ >>> escape_gle_text("x^2")
440
+ 'x\\\\char{94}2'
441
+ >>> escape_gle_text(escape_gle_text("x^2")) # idempotent
442
+ 'x\\\\char{94}2'
443
+ >>> escape_gle_text(r"\\chi{} (emu/mol)") # markup passes through
444
+ '\\\\chi{} (emu/mol)'
445
+ """
446
+ out: List[str] = []
447
+ i, n = 0, len(s)
448
+ while i < n:
449
+ c = s[i]
450
+
451
+ if c == "\\":
452
+ # GLE markup: copy the macro token, plus any brace groups that
453
+ # belong to it (\char{95}, \rule{2}{4}, \raise{0.1em}{x}).
454
+ j = i + 1
455
+ while j < n and s[j].isalpha():
456
+ j += 1
457
+ if j == i + 1: # backslash + non-letter (\_, \,, \\ ...)
458
+ j = min(i + 2, n)
459
+ out.append(s[i:j])
460
+ i = j
461
+ while i < n and s[i] == "{":
462
+ end = _brace_end(s, i)
463
+ if end is None:
464
+ break
465
+ out.append(s[i:end])
466
+ i = end
467
+ continue
468
+
469
+ if c in "_^" and i + 1 < n and s[i + 1] == "{":
470
+ # A *braced* script is GLE markup, not literal text: it is what
471
+ # the math translator emits (``x_{i}^{2}``) and what the GLE
472
+ # markup spelling of a subscript looks like (``T_{N}``). Only a
473
+ # bare ``_``/``^`` -- the accident in ``lambda_tail`` -- is
474
+ # escaped. Keeping these verbatim is also what makes translating
475
+ # an already-translated string a no-op.
476
+ end = _brace_end(s, i + 1)
477
+ if end is not None:
478
+ out.append(s[i:end])
479
+ i = end
480
+ continue
481
+
482
+ if c == "{":
483
+ end = _brace_end(s, i)
484
+ if end is not None and _opens_with_macro(s[i + 1 : end - 1]):
485
+ # A font/markup group such as ``{\bf bold}``.
486
+ out.append(s[i:end])
487
+ i = end
488
+ continue
489
+
490
+ out.append(TEXT_ESCAPES.get(c, c))
491
+ i += 1
492
+
493
+ return "".join(out)
494
+
495
+
496
+ def _brace_end(s: str, i: int) -> Optional[int]:
497
+ """Index just past the ``}`` matching the ``{`` at *i*, or None if unclosed."""
498
+ depth = 0
499
+ j, n = i, len(s)
500
+ while j < n:
501
+ ch = s[j]
502
+ if ch == "\\":
503
+ j += 2
504
+ continue
505
+ if ch == "{":
506
+ depth += 1
507
+ elif ch == "}":
508
+ depth -= 1
509
+ if depth == 0:
510
+ return j + 1
511
+ j += 1
512
+ return None
513
+
514
+
515
+ def _opens_with_macro(inner: str) -> bool:
516
+ """True if a brace group's contents start with a ``\\macro`` token."""
517
+ stripped = inner.lstrip()
518
+ return len(stripped) >= 2 and stripped[0] == "\\" and stripped[1].isalpha()
519
+
520
+
521
+ def _next_char(rendered: List[Tuple[str, bool]], start: int) -> Optional[str]:
522
+ """First character of the concatenation of segments from *start* onward."""
523
+ for text, _ in rendered[start:]:
524
+ if text:
525
+ return text[0]
526
+ return None
527
+
528
+
529
+ def _split_segments(s: str) -> Optional[List[Tuple[str, str]]]:
530
+ """Split *s* into alternating ``('text'|'math', content)`` segments.
531
+
532
+ ``\\$`` is treated as a literal ``$`` (in both text and math) and never
533
+ acts as a delimiter. Returns ``None`` when the unescaped ``$`` count is
534
+ odd (an unterminated math segment).
535
+ """
536
+ segments: List[Tuple[str, str]] = []
537
+ buf: List[str] = []
538
+ in_math = False
539
+ i, n = 0, len(s)
540
+ while i < n:
541
+ c = s[i]
542
+ if c == "\\" and i + 1 < n and s[i + 1] == "$":
543
+ buf.append("$") # literal dollar, not a delimiter
544
+ i += 2
545
+ continue
546
+ if c == "$":
547
+ segments.append(("math" if in_math else "text", "".join(buf)))
548
+ buf = []
549
+ in_math = not in_math
550
+ i += 1
551
+ continue
552
+ buf.append(c)
553
+ i += 1
554
+ if in_math:
555
+ return None
556
+ segments.append(("text", "".join(buf)))
557
+ return segments
558
+
559
+
560
+ def _translate_math(m: str) -> str:
561
+ """Translate the interior of one ``$...$`` segment into GLE markup."""
562
+ out: List[str] = []
563
+ i, n = 0, len(m)
564
+ while i < n:
565
+ c = m[i]
566
+ if c == "\\":
567
+ token, i = _read_macro(m, i)
568
+ out.append(token)
569
+ elif c in "^_":
570
+ token, i = _read_script(m, i)
571
+ out.append(token)
572
+ elif c == "{":
573
+ # Bare TeX grouping (invisible in matplotlib). Strip the braces so
574
+ # GLE does not render literal braces; keep the translated contents.
575
+ group, i = _read_brace_group(m, i)
576
+ out.append(_translate_math(group))
577
+ elif c == "}":
578
+ i += 1 # stray closing brace: drop it
579
+ else:
580
+ out.append(c)
581
+ i += 1
582
+ return "".join(out)
583
+
584
+
585
+ def _read_macro(m: str, i: int) -> Tuple[str, int]:
586
+ """Read a ``\\...`` macro starting at index *i* (m[i] == '\\')."""
587
+ j = i + 1
588
+ if j >= len(m):
589
+ return "", j # trailing backslash -> drop
590
+ # Backslash + non-letter: spacing / escaped-symbol macro.
591
+ if not m[j].isalpha():
592
+ ch = m[j]
593
+ return _SYMBOL_ESCAPES.get(ch, ch), j + 1
594
+ # Backslash + letters: a named macro.
595
+ k = j
596
+ while k < len(m) and m[k].isalpha():
597
+ k += 1
598
+ name = m[j:k]
599
+
600
+ if name == "frac":
601
+ return _read_frac(m, k)
602
+
603
+ if name in FONT_MACROS:
604
+ group, after = _read_optional_group(m, k)
605
+ if group is None:
606
+ # No brace group followed: emit as a bare pass-through macro.
607
+ return "\\" + name, k
608
+ inner = _translate_math(group)
609
+ font = FONT_MACROS[name]
610
+ if font is None:
611
+ return inner, after # unsupported family -> strip to contents
612
+ return "{\\" + font + " " + inner + "}", after
613
+
614
+ # Known GLE symbol macro, or an unknown macro we pass through verbatim
615
+ # (GLE understands more than we enumerate; passing through preserves
616
+ # user intent). Either way emit ``\name``.
617
+ return "\\" + name, k
618
+
619
+
620
+ def _read_script(m: str, i: int) -> Tuple[str, int]:
621
+ """Read a ``^``/``_`` script at index *i* and return a braced GLE form."""
622
+ op = m[i] # '^' or '_'
623
+ j = i + 1
624
+ if j >= len(m):
625
+ return op, j # dangling ^ or _ : emit literally
626
+ c = m[j]
627
+ if c == "{":
628
+ group, after = _read_brace_group(m, j)
629
+ return op + "{" + _translate_math(group) + "}", after
630
+ if c == "\\":
631
+ token, after = _read_macro(m, j)
632
+ return op + "{" + token + "}", after
633
+ # Single character token.
634
+ return op + "{" + c + "}", j + 1
635
+
636
+
637
+ def _read_frac(m: str, i: int) -> Tuple[str, int]:
638
+ """Degrade ``\\frac{a}{b}`` (no GLE inline equivalent) to ``a/b``."""
639
+ num, i = _read_optional_group(m, i)
640
+ den, i = _read_optional_group(m, i)
641
+ num_s = _translate_math(num) if num is not None else ""
642
+ den_s = _translate_math(den) if den is not None else ""
643
+ return num_s + "/" + den_s, i
644
+
645
+
646
+ def _read_optional_group(m: str, i: int) -> Tuple[Optional[str], int]:
647
+ """If m[i] opens a ``{...}`` group return (contents, index_after); skips
648
+ leading whitespace. Otherwise return (None, i)."""
649
+ j = i
650
+ while j < len(m) and m[j].isspace():
651
+ j += 1
652
+ if j < len(m) and m[j] == "{":
653
+ return _read_brace_group(m, j)
654
+ return None, i
655
+
656
+
657
+ def _read_brace_group(m: str, i: int) -> Tuple[str, int]:
658
+ """Read a balanced ``{...}`` group at index *i* (m[i] == '{').
659
+
660
+ Returns (inner_contents_without_outer_braces, index_after_closing_brace).
661
+ Tolerates an unclosed group by consuming to end of string.
662
+ """
663
+ assert m[i] == "{"
664
+ depth = 0
665
+ j = i
666
+ n = len(m)
667
+ while j < n:
668
+ ch = m[j]
669
+ if ch == "\\":
670
+ j += 2 # skip escaped char
671
+ continue
672
+ if ch == "{":
673
+ depth += 1
674
+ elif ch == "}":
675
+ depth -= 1
676
+ if depth == 0:
677
+ return m[i + 1 : j], j + 1
678
+ j += 1
679
+ return m[i + 1 :], n # unterminated -> take the rest