File size: 20,812 Bytes
5655a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
// Best-effort LaTeX โ†’ Unicode for inline / display math captured by the
// markdown renderer. The terminal can't typeset LaTeX, but Unicode covers
// most of what models actually emit: Greek letters, blackboard / fraktur /
// calligraphic capitals, set theory + logic operators, common arrows,
// sub/superscripts, and `\frac{a}{b}` collapsed to `a/b`.
//
// Design rules:
//   โ€ข Pure regex pipeline. Anything we don't recognise is preserved
//     verbatim (so a `\foo{bar}` we've never heard of still survives).
//     A real LaTeX parser would be more correct but throws on partial
//     input โ€” terminal users would rather see the raw command than a
//     parse-error placeholder.
//   โ€ข Longest-match-first ordering on commands so `\le` doesn't shadow
//     `\leq`, `\sub` doesn't shadow `\subseteq`, etc.
//   โ€ข Word-boundary lookahead `(?![A-Za-z])` after each command so
//     `\pix` (made-up command) doesn't get partially substituted as `ฯ€`.
//   โ€ข `\mathbb{X}`, `\mathcal{X}`, `\mathfrak{X}` only handle a single
//     letter argument โ€” multi-letter `\mathbb{NN}` is rare and would
//     need a real parser to do correctly.
//   โ€ข Sub/super scripts only convert if EVERY character has a Unicode
//     equivalent. Mixed content like `^{n+1}` falls back to the raw
//     LaTeX so we don't emit `โฟ+ยน` (which has no `+` superscript glyph
//     in some fonts and reads worse than the source).

const SYMBOLS: Record<string, string> = {
  // Greek lowercase
  '\\alpha': 'ฮฑ',
  '\\beta': 'ฮฒ',
  '\\gamma': 'ฮณ',
  '\\delta': 'ฮด',
  '\\epsilon': 'ฮต',
  '\\varepsilon': 'ฮต',
  '\\zeta': 'ฮถ',
  '\\eta': 'ฮท',
  '\\theta': 'ฮธ',
  '\\vartheta': 'ฯ‘',
  '\\iota': 'ฮน',
  '\\kappa': 'ฮบ',
  '\\lambda': 'ฮป',
  '\\mu': 'ฮผ',
  '\\nu': 'ฮฝ',
  '\\xi': 'ฮพ',
  '\\pi': 'ฯ€',
  '\\varpi': 'ฯ–',
  '\\rho': 'ฯ',
  '\\varrho': 'ฯฑ',
  '\\sigma': 'ฯƒ',
  '\\varsigma': 'ฯ‚',
  '\\tau': 'ฯ„',
  '\\upsilon': 'ฯ…',
  '\\phi': 'ฯ†',
  '\\varphi': 'ฯ†',
  '\\chi': 'ฯ‡',
  '\\psi': 'ฯˆ',
  '\\omega': 'ฯ‰',

  // Greek uppercase
  '\\Gamma': 'ฮ“',
  '\\Delta': 'ฮ”',
  '\\Theta': 'ฮ˜',
  '\\Lambda': 'ฮ›',
  '\\Xi': 'ฮž',
  '\\Pi': 'ฮ ',
  '\\Sigma': 'ฮฃ',
  '\\Upsilon': 'ฮฅ',
  '\\Phi': 'ฮฆ',
  '\\Psi': 'ฮจ',
  '\\Omega': 'ฮฉ',

  // Big operators
  '\\sum': 'โˆ‘',
  '\\prod': 'โˆ',
  '\\coprod': 'โˆ',
  '\\int': 'โˆซ',
  '\\iint': 'โˆฌ',
  '\\iiint': 'โˆญ',
  '\\oint': 'โˆฎ',
  '\\bigcup': 'โ‹ƒ',
  '\\bigcap': 'โ‹‚',
  '\\bigvee': 'โ‹',
  '\\bigwedge': 'โ‹€',
  '\\bigoplus': 'โจ',
  '\\bigotimes': 'โจ‚',

  // Calculus
  '\\partial': 'โˆ‚',
  '\\nabla': 'โˆ‡',
  '\\sqrt': 'โˆš',

  // Sets
  '\\emptyset': 'โˆ…',
  '\\varnothing': 'โˆ…',
  '\\infty': 'โˆž',
  '\\in': 'โˆˆ',
  '\\notin': 'โˆ‰',
  '\\ni': 'โˆ‹',
  '\\subset': 'โŠ‚',
  '\\supset': 'โŠƒ',
  '\\subseteq': 'โІ',
  '\\supseteq': 'โЇ',
  '\\subsetneq': 'โŠŠ',
  '\\supsetneq': 'โŠ‹',
  '\\cup': 'โˆช',
  '\\cap': 'โˆฉ',
  '\\setminus': 'โˆ–',
  '\\complement': 'โˆ',

  // Logic
  '\\forall': 'โˆ€',
  '\\exists': 'โˆƒ',
  '\\nexists': 'โˆ„',
  '\\land': 'โˆง',
  '\\lor': 'โˆจ',
  '\\lnot': 'ยฌ',
  '\\neg': 'ยฌ',
  '\\therefore': 'โˆด',
  '\\because': 'โˆต',

  // Relations
  '\\le': 'โ‰ค',
  '\\leq': 'โ‰ค',
  '\\ge': 'โ‰ฅ',
  '\\geq': 'โ‰ฅ',
  '\\ne': 'โ‰ ',
  '\\neq': 'โ‰ ',
  '\\ll': 'โ‰ช',
  '\\gg': 'โ‰ซ',
  '\\approx': 'โ‰ˆ',
  '\\equiv': 'โ‰ก',
  '\\cong': 'โ‰…',
  '\\sim': 'โˆผ',
  '\\simeq': 'โ‰ƒ',
  '\\propto': 'โˆ',
  '\\perp': 'โŠฅ',
  '\\parallel': 'โˆฅ',
  '\\models': 'โŠจ',
  '\\vdash': 'โŠข',
  '\\mid': 'โˆฃ',
  '\\nmid': 'โˆค',
  '\\divides': 'โˆฃ',

  // Common standalone glyphs
  '\\blacksquare': 'โ– ',
  '\\square': 'โ–ก',
  '\\Box': 'โ–ก',
  '\\qed': 'โˆŽ',
  '\\bigstar': 'โ˜…',

  // Modular arithmetic โ€” the `\pmod{p}` form (with arg) is handled below;
  // the bare `\bmod` / `\mod` commands are simple text substitutions.
  '\\bmod': 'mod',
  '\\mod': 'mod',

  // Brackets / fences (named delimiter commands; the `\left\X` / `\right\X`
  // unwrapping below leaves these behind for the symbol pass to resolve).
  '\\langle': 'โŸจ',
  '\\rangle': 'โŸฉ',
  '\\lceil': 'โŒˆ',
  '\\rceil': 'โŒ‰',
  '\\lfloor': 'โŒŠ',
  '\\rfloor': 'โŒ‹',
  '\\|': 'โ€–',

  // Arrows
  '\\to': 'โ†’',
  '\\rightarrow': 'โ†’',
  '\\leftarrow': 'โ†',
  '\\leftrightarrow': 'โ†”',
  '\\Rightarrow': 'โ‡’',
  '\\Leftarrow': 'โ‡',
  '\\Leftrightarrow': 'โ‡”',
  '\\implies': 'โŸน',
  '\\impliedby': 'โŸธ',
  '\\iff': 'โŸบ',
  '\\mapsto': 'โ†ฆ',
  '\\hookrightarrow': 'โ†ช',
  '\\hookleftarrow': 'โ†ฉ',
  '\\uparrow': 'โ†‘',
  '\\downarrow': 'โ†“',
  '\\updownarrow': 'โ†•',

  // Binary operators
  '\\cdot': 'โ‹…',
  '\\cdots': 'โ‹ฏ',
  '\\ldots': 'โ€ฆ',
  '\\dots': 'โ€ฆ',
  '\\dotsb': 'โ€ฆ',
  '\\dotsc': 'โ€ฆ',
  '\\vdots': 'โ‹ฎ',
  '\\ddots': 'โ‹ฑ',
  '\\times': 'ร—',
  '\\div': 'รท',
  '\\pm': 'ยฑ',
  '\\mp': 'โˆ“',
  '\\circ': 'โˆ˜',
  '\\bullet': 'โ€ข',
  '\\star': 'โ‹†',
  '\\ast': 'โˆ—',
  '\\oplus': 'โŠ•',
  '\\ominus': 'โŠ–',
  '\\otimes': 'โŠ—',
  '\\odot': 'โŠ™',
  '\\diamond': 'โ‹„',
  '\\angle': 'โˆ ',
  '\\triangle': 'โ–ณ',

  // Spacing โ€” collapse to varying widths of regular space
  '\\,': ' ',
  '\\;': ' ',
  '\\:': ' ',
  '\\!': '',
  '\\ ': ' ',
  '\\quad': '  ',
  '\\qquad': '    ',

  // Functions (LaTeX renders these in roman; we just keep the name)
  '\\sin': 'sin',
  '\\cos': 'cos',
  '\\tan': 'tan',
  '\\cot': 'cot',
  '\\sec': 'sec',
  '\\csc': 'csc',
  '\\arcsin': 'arcsin',
  '\\arccos': 'arccos',
  '\\arctan': 'arctan',
  '\\sinh': 'sinh',
  '\\cosh': 'cosh',
  '\\tanh': 'tanh',
  '\\log': 'log',
  '\\ln': 'ln',
  '\\exp': 'exp',
  '\\det': 'det',
  '\\dim': 'dim',
  '\\ker': 'ker',
  '\\lim': 'lim',
  '\\liminf': 'liminf',
  '\\limsup': 'limsup',
  '\\sup': 'sup',
  '\\inf': 'inf',
  '\\max': 'max',
  '\\min': 'min',
  '\\arg': 'arg',
  '\\gcd': 'gcd',

  // Escaped literals โ€” model occasionally emits these for display
  '\\&': '&',
  '\\%': '%',
  '\\$': '$',
  '\\#': '#',
  '\\_': '_',
  '\\{': '{',
  '\\}': '}'
}

const BB: Record<string, string> = {
  A: '๐”ธ',
  B: '๐”น',
  C: 'โ„‚',
  D: '๐”ป',
  E: '๐”ผ',
  F: '๐”ฝ',
  G: '๐”พ',
  H: 'โ„',
  I: '๐•€',
  J: '๐•',
  K: '๐•‚',
  L: '๐•ƒ',
  M: '๐•„',
  N: 'โ„•',
  O: '๐•†',
  P: 'โ„™',
  Q: 'โ„š',
  R: 'โ„',
  S: '๐•Š',
  T: '๐•‹',
  U: '๐•Œ',
  V: '๐•',
  W: '๐•Ž',
  X: '๐•',
  Y: '๐•',
  Z: 'โ„ค'
}

const CAL: Record<string, string> = {
  A: '๐’œ',
  B: 'โ„ฌ',
  C: '๐’ž',
  D: '๐’Ÿ',
  E: 'โ„ฐ',
  F: 'โ„ฑ',
  G: '๐’ข',
  H: 'โ„‹',
  I: 'โ„',
  J: '๐’ฅ',
  K: '๐’ฆ',
  L: 'โ„’',
  M: 'โ„ณ',
  N: '๐’ฉ',
  O: '๐’ช',
  P: '๐’ซ',
  Q: '๐’ฌ',
  R: 'โ„›',
  S: '๐’ฎ',
  T: '๐’ฏ',
  U: '๐’ฐ',
  V: '๐’ฑ',
  W: '๐’ฒ',
  X: '๐’ณ',
  Y: '๐’ด',
  Z: '๐’ต'
}

const FRAK: Record<string, string> = {
  A: '๐”„',
  B: '๐”…',
  C: 'โ„ญ',
  D: '๐”‡',
  E: '๐”ˆ',
  F: '๐”‰',
  G: '๐”Š',
  H: 'โ„Œ',
  I: 'โ„‘',
  J: '๐”',
  K: '๐”Ž',
  L: '๐”',
  M: '๐”',
  N: '๐”‘',
  O: '๐”’',
  P: '๐”“',
  Q: '๐””',
  R: 'โ„œ',
  S: '๐”–',
  T: '๐”—',
  U: '๐”˜',
  V: '๐”™',
  W: '๐”š',
  X: '๐”›',
  Y: '๐”œ',
  Z: 'โ„จ'
}

const SUPERSCRIPT: Record<string, string> = {
  '0': 'โฐ',
  '1': 'ยน',
  '2': 'ยฒ',
  '3': 'ยณ',
  '4': 'โด',
  '5': 'โต',
  '6': 'โถ',
  '7': 'โท',
  '8': 'โธ',
  '9': 'โน',
  '+': 'โบ',
  '-': 'โป',
  '=': 'โผ',
  '(': 'โฝ',
  ')': 'โพ',
  a: 'แตƒ',
  b: 'แต‡',
  c: 'แถœ',
  d: 'แตˆ',
  e: 'แต‰',
  f: 'แถ ',
  g: 'แต',
  h: 'สฐ',
  i: 'โฑ',
  j: 'สฒ',
  k: 'แต',
  l: 'หก',
  m: 'แต',
  n: 'โฟ',
  o: 'แต’',
  p: 'แต–',
  r: 'สณ',
  s: 'หข',
  t: 'แต—',
  u: 'แต˜',
  v: 'แต›',
  w: 'สท',
  x: 'หฃ',
  y: 'สธ',
  z: 'แถป'
}

const SUBSCRIPT: Record<string, string> = {
  '0': 'โ‚€',
  '1': 'โ‚',
  '2': 'โ‚‚',
  '3': 'โ‚ƒ',
  '4': 'โ‚„',
  '5': 'โ‚…',
  '6': 'โ‚†',
  '7': 'โ‚‡',
  '8': 'โ‚ˆ',
  '9': 'โ‚‰',
  '+': 'โ‚Š',
  '-': 'โ‚‹',
  '=': 'โ‚Œ',
  '(': 'โ‚',
  ')': 'โ‚Ž',
  a: 'โ‚',
  e: 'โ‚‘',
  h: 'โ‚•',
  i: 'แตข',
  j: 'โฑผ',
  k: 'โ‚–',
  l: 'โ‚—',
  m: 'โ‚˜',
  n: 'โ‚™',
  o: 'โ‚’',
  p: 'โ‚š',
  r: 'แตฃ',
  s: 'โ‚›',
  t: 'โ‚œ',
  u: 'แตค',
  v: 'แตฅ',
  x: 'โ‚“'
}

// Sentinel control characters used to mark `\boxed` / `\fbox` regions in
// the converted output. The renderer splits on these to apply a highlight
// style; consumers that don't want highlighting can strip them with the
// exported `BOX_RE` below.
export const BOX_OPEN = '\u0001'
export const BOX_CLOSE = '\u0002'
// eslint-disable-next-line no-control-regex -- intentional sentinel control chars
export const BOX_RE = /\u0001([^\u0001\u0002]*)\u0002/g

const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

// Pre-compile two symbol regexes: one for letter-ending commands (`\pi`,
// `\sum`) which need a `(?![A-Za-z])` lookahead so they don't partially
// match `\pix` or `\summa`, and one for punctuation-ending commands
// (`\{`, `\,`, `\|`) which must NOT have the lookahead โ€” otherwise
// `\{p` would refuse to substitute because `p` is a letter.
//
// Longest commands first inside each group so `\leq` beats `\le`.
const splitByEnding = (keys: string[]) => {
  const letter: string[] = []
  const punct: string[] = []

  for (const k of keys) {
    if (/[A-Za-z]$/.test(k)) {
      letter.push(k)
    } else {
      punct.push(k)
    }
  }

  return { letter, punct }
}

const buildAlt = (cmds: string[]) =>
  cmds
    .sort((a, b) => b.length - a.length)
    .map(escapeRe)
    .join('|')

const { letter: LETTER_CMDS, punct: PUNCT_CMDS } = splitByEnding(Object.keys(SYMBOLS))

const SYMBOL_LETTER_RE = new RegExp('(?:' + buildAlt(LETTER_CMDS) + ')(?![A-Za-z])', 'g')
const SYMBOL_PUNCT_RE = new RegExp('(?:' + buildAlt(PUNCT_CMDS) + ')', 'g')

const convertScript = (input: string, table: Record<string, string>, sigil: '^' | '_'): string => {
  let out = ''
  let allMapped = true

  for (const ch of input) {
    const mapped = table[ch]

    if (!mapped) {
      allMapped = false

      break
    }

    out += mapped
  }

  if (allMapped) {
    return out
  }

  // Fallback: if the body is a single visible character (e.g. `โˆž` after
  // earlier symbol substitution), render it without braces โ€” `^โˆž` reads
  // far better than `^{โˆž}` in a terminal. Multi-char bodies that don't
  // fully convert use parens (`e^(iฯ€)`) instead of braces (`e^{iฯ€}`)
  // because parens are normal punctuation while braces look like
  // unrendered LaTeX.
  const trimmed = input.trim()

  if ([...trimmed].length === 1) {
    return `${sigil}${trimmed}`
  }

  return `${sigil}(${trimmed})`
}

// Walk the string and parse `{...}` honouring nested braces. Unlike a
// `\{[^{}]*\}` regex this survives `\frac{|t|^{p-1}|P(t)|^p}{...}` where
// the numerator contains its own braces from a superscript. Returns the
// inner content (without the outer braces) and the offset just past the
// closing `}`. Returns null if there is no balanced brace at `start`.
const readBraced = (s: string, start: number): { content: string; end: number } | null => {
  if (s[start] !== '{') {
    return null
  }

  let depth = 1
  let i = start + 1

  while (i < s.length && depth > 0) {
    const c = s[i]

    // Skip escapes โ€” `\{` and `\}` inside a body are literal braces and
    // should not change the brace counter.
    if (c === '\\' && i + 1 < s.length) {
      i += 2

      continue
    }

    if (c === '{') {
      depth++
    } else if (c === '}') {
      depth--
    }

    if (depth > 0) {
      i++
    }
  }

  if (depth !== 0) {
    return null
  }

  return { content: s.slice(start + 1, i), end: i + 1 }
}

// Replace every occurrence of `\command{arg}` using balanced-brace parsing
// (so `\boxed{x^{n+1}}` works where a `[^{}]*` regex would fail). The
// `render` callback receives the inner content already recursed-into, so
// `\boxed{\boxed{x}}` resolves outside-in cleanly. Unmatched `\command`
// (no following `{...}`) is preserved verbatim.
const replaceBracedCommand = (input: string, command: string, render: (content: string) => string): string => {
  const cmdLen = command.length
  let out = ''
  let i = 0

  while (i < input.length) {
    const idx = input.indexOf(command, i)

    if (idx < 0) {
      out += input.slice(i)

      return out
    }

    const after = input[idx + cmdLen]

    if (after && /[A-Za-z]/.test(after)) {
      out += input.slice(i, idx + cmdLen)
      i = idx + cmdLen

      continue
    }

    out += input.slice(i, idx)

    let p = idx + cmdLen

    while (input[p] === ' ' || input[p] === '\t') {
      p++
    }

    const arg = readBraced(input, p)

    if (!arg) {
      out += input.slice(idx, p + 1)
      i = p + 1

      continue
    }

    out += render(replaceBracedCommand(arg.content, command, render))
    i = arg.end
  }

  return out
}

// Replace every `\frac{num}{den}` with `num/den` (parens around either
// side when its precedence demands it). The recursion handles nested
// fractions naturally: `\frac{1}{\frac{1}{x}}` collapses to `1/(1/x)`
// because we recurse into `den` before deciding whether to parenthesise.
const replaceFracs = (input: string): string => {
  let out = ''
  let i = 0

  while (i < input.length) {
    const idx = input.indexOf('\\frac', i)

    if (idx < 0) {
      out += input.slice(i)

      return out
    }

    const after = input[idx + 5]

    // `(?![A-Za-z])` โ€” protect hypothetical commands like `\fraction`.
    if (after && /[A-Za-z]/.test(after)) {
      out += input.slice(i, idx + 5)
      i = idx + 5

      continue
    }

    out += input.slice(i, idx)

    let p = idx + 5

    while (input[p] === ' ' || input[p] === '\t') {
      p++
    }

    const num = readBraced(input, p)

    if (!num) {
      out += input.slice(idx, p + 1)
      i = p + 1

      continue
    }

    p = num.end

    while (input[p] === ' ' || input[p] === '\t') {
      p++
    }

    const den = readBraced(input, p)

    if (!den) {
      out += input.slice(idx, p + 1)
      i = p + 1

      continue
    }

    out += `${wrapForFrac(replaceFracs(num.content))}/${wrapForFrac(replaceFracs(den.content))}`
    i = den.end
  }

  return out
}

// Wrap multi-token expressions in parens so `\frac{a+b}{c}` becomes
// `(a+b)/c` rather than `a+b/c`. We wrap whenever inline `/` would
// change the meaning โ€” that's any binary operator (`+`, `-`, `*`, `/`)
// or whitespace separating tokens. `*` and `/` matter because nested
// fractions and products like `\frac{a*b}{c}` and `\frac{1/x}{y}` would
// otherwise read as `a*b/c` (right-associative ambiguity) and `1/x/y`.
// Atomic factors like `n!`, `x^2`, `\sin x` don't trigger any of these
// and stay un-parenthesised โ€” wrapping them just clutters the output.
const wrapForFrac = (expr: string) => {
  const trimmed = expr.trim()

  if (!trimmed) {
    return trimmed
  }

  if (/^\(.*\)$/.test(trimmed)) {
    return trimmed
  }

  if (/[+\-/*]|\s/.test(trimmed)) {
    return `(${trimmed})`
  }

  return trimmed
}

export function texToUnicode(input: string): string {
  let s = input

  s = s.replace(/\\mathbb\s*\{([A-Za-z])\}/g, (raw, c: string) => BB[c] ?? raw)
  s = s.replace(/\\mathcal\s*\{([A-Za-z])\}/g, (raw, c: string) => CAL[c] ?? raw)
  s = s.replace(/\\mathfrak\s*\{([A-Za-z])\}/g, (raw, c: string) => FRAK[c] ?? raw)
  s = s.replace(/\\mathbf\s*\{([^{}]+)\}/g, (_, c: string) => c)
  s = s.replace(/\\mathit\s*\{([^{}]+)\}/g, (_, c: string) => c)
  s = s.replace(/\\mathrm\s*\{([^{}]+)\}/g, (_, c: string) => c)
  s = s.replace(/\\text\s*\{([^{}]+)\}/g, (_, c: string) => c)
  s = s.replace(/\\operatorname\s*\{([^{}]+)\}/g, (_, c: string) => c)

  s = s.replace(/\\overline\s*\{([^{}]+)\}/g, (_, c: string) => `${c}\u0305`)
  s = s.replace(/\\hat\s*\{([^{}]+)\}/g, (_, c: string) => `${c}\u0302`)
  s = s.replace(/\\bar\s*\{([^{}]+)\}/g, (_, c: string) => `${c}\u0304`)
  s = s.replace(/\\tilde\s*\{([^{}]+)\}/g, (_, c: string) => `${c}\u0303`)
  s = s.replace(/\\vec\s*\{([^{}]+)\}/g, (_, c: string) => `${c}\u20D7`)
  s = s.replace(/\\dot\s*\{([^{}]+)\}/g, (_, c: string) => `${c}\u0307`)
  s = s.replace(/\\ddot\s*\{([^{}]+)\}/g, (_, c: string) => `${c}\u0308`)

  s = replaceFracs(s)

  // `\boxed{X}` / `\fbox{X}` highlight a final answer. Terminals can't
  // draw a real box, so we wrap the content in U+0001 / U+0002 control
  // characters โ€” non-printable, never present in real text โ€” and let the
  // markdown renderer split on them and apply a highlight style (inverse
  // video) to the bracketed region. This keeps `texToUnicode` pure-string
  // while letting the React layer do the actual visual emphasis.
  // Argument is parsed with balanced braces so nested `{...}` from
  // superscripts / fractions inside the box survive.
  s = replaceBracedCommand(s, '\\boxed', body => `${BOX_OPEN}${body.trim()}${BOX_CLOSE}`)
  s = replaceBracedCommand(s, '\\fbox', body => `${BOX_OPEN}${body.trim()}${BOX_CLOSE}`)

  // `\xrightarrow{label}` / `\xleftarrow{label}` collapse to an arrow with
  // the label inline. LaTeX renders the label above the arrow; in monospace
  // we put it adjacent โ€” `โ”€labelโ†’` is the closest readable approximation.
  // Run before the symbol pass so the label can still pick up Greek and
  // operator substitutions afterwards.
  s = s.replace(/\\xrightarrow\s*\{([^{}]*)\}/g, (_, label: string) => `โ”€${label.trim()}โ†’`)
  s = s.replace(/\\xleftarrow\s*\{([^{}]*)\}/g, (_, label: string) => `โ†${label.trim()}โ”€`)
  s = s.replace(/\\Longrightarrow/g, 'โŸน')
  s = s.replace(/\\Longleftarrow/g, 'โŸธ')
  s = s.replace(/\\Longleftrightarrow/g, 'โŸบ')

  // `\pmod{p}` โ†’ ` (mod p)` (LaTeX adds parens automatically); `\pod{p}`
  // is a paren-less variant; `\tag{n}` is the equation-number annotation
  // shown to the right of an equation. Collapse to a single-space-prefixed
  // bracketed form. The leading `\s*` in the pattern absorbs any whitespace
  // already in the source so we don't end up with `b  (mod p)` (double
  // space) when the user wrote `b \pmod{p}`.
  s = s.replace(/\s*\\pmod\s*\{([^{}]*)\}/g, (_, p: string) => ` (mod ${p.trim()})`)
  s = s.replace(/\s*\\pod\s*\{([^{}]*)\}/g, (_, p: string) => ` (${p.trim()})`)
  s = s.replace(/\s*\\tag\s*\{([^{}]*)\}/g, (_, n: string) => ` (${n.trim()})`)

  // `\big`, `\Big`, `\bigg`, `\Bigg` (with optional `l`/`r`/`m` suffix)
  // are sizing wrappers analogous to `\left`/`\right` but without the
  // automatic-pairing semantics. Strip them and leave whatever delimiter
  // follows. The trailing `(?![A-Za-z])` protects `\bigtriangleup` and
  // any other letter-continuation command from being shaved.
  s = s.replace(/\\(?:Bigg|bigg|Big|big)[lrm]?(?![A-Za-z])/g, '')

  // Style / size hints that don't typeset any glyph and only affect how
  // things would be sized in a real LaTeX engine. In a terminal every
  // glyph is one monospace cell, so there's nothing to do โ€” drop them
  // (with any trailing whitespace) so they don't leak through as raw
  // `\displaystyle` in the output.
  s = s.replace(/\\(?:scriptscriptstyle|displaystyle|scriptstyle|textstyle|nolimits|limits)(?![A-Za-z])\s*/g, '')

  // `\left` and `\right` are sizing wrappers around any delimiter โ€” bare
  // (`\left(`), escaped (`\left\{`), or named (`\left\langle`). Strip the
  // wrapper unconditionally and let the rest of the pipeline (or the
  // upcoming symbol pass) handle whatever delimiter follows. The optional
  // `.?` consumes `\left.` / `\right.` which mean "no delimiter".
  // Lookahead `(?![A-Za-z])` keeps `\leftarrow` / `\leftrightarrow` safe.
  s = s.replace(/\\left(?![A-Za-z])\.?/g, '')
  s = s.replace(/\\right(?![A-Za-z])\.?/g, '')

  // Run symbol substitution BEFORE scripts so a body like `^{\infty}`
  // becomes `^{โˆž}` first; convertScript can then either map โˆž to a
  // superscript (it can't โ€” Unicode lacks one) or fall back to `^โˆž`
  // by stripping braces around the now-single-character body.
  //
  // Punctuation pass first โ€” these can be followed by letters (`\{p`
  // is "open-brace then p"), so the letter pass's `(?![A-Za-z])` rule
  // would wrongly block them.
  s = s.replace(SYMBOL_PUNCT_RE, m => SYMBOLS[m] ?? m)
  s = s.replace(SYMBOL_LETTER_RE, m => SYMBOLS[m] ?? m)

  // Bare `^c` / `_c` handles ONLY alphanumerics and `+`/`-`/`=`. Parens
  // are intentionally excluded because the braced-fallback above can
  // emit `(...)` and we don't want a second pass to greedily convert
  // its opening paren into `โฝ` and orphan the closing one.
  s = s.replace(/\^\s*\{([^{}]+)\}/g, (_, body: string) => convertScript(body, SUPERSCRIPT, '^'))
  s = s.replace(/\^([A-Za-z0-9+\-=])/g, (raw, ch: string) => SUPERSCRIPT[ch] ?? raw)
  s = s.replace(/_\s*\{([^{}]+)\}/g, (_, body: string) => convertScript(body, SUBSCRIPT, '_'))
  s = s.replace(/_([A-Za-z0-9+\-=])/g, (raw, ch: string) => SUBSCRIPT[ch] ?? raw)

  return s
}