mt-core 0.2.1

Equation model: rows, characters and templates in the shape the editor and renderers share.
Documentation
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
//! The character-to-class conventions the formats follow.
//!
//! MTEF records the typeface of every character but not its atom class, Office Math records
//! neither, and MathML records the class only where it differs from its own defaults. Every
//! reader therefore derives a character's class from the character itself, and the writer of a
//! format that has defaults needs the same answer to know when it has to write the class out.
//! The preview also needs it, because it draws a character with the face MathType drew it with.
//!
//! Two conventions cover that work, and each format names the one it follows:
//!
//! * [`Convention::MathType`] is the class MathType's own output implies, taken from the TeX
//!   classes. The MTEF reader and writer and the preview use it.
//! * [`Convention::Markup`] is the default class MathML's writer and reader share. Office Math
//!   follows it too, since it records no class at all. MathML spaces `mo` by its operator
//!   dictionary rather than by the TeX classes, so the two conventions disagree about `/`, which
//!   is a binary operator in the markup convention and an ordinary character in MathType, about
//!   `:`, which is punctuation in the markup convention and a relation in MathType, and about the
//!   characters MathType classes as operators or relations while the markup convention leaves
//!   them ordinary. Those are the circled n-ary operators 2A00 and 2A03 to 2A06, the union and
//!   intersection signs 2229 and 222A, the arrows 2191, 2193, 2194, 21A6, 27F9 and 27FA, and the
//!   relations 220B, 2223, 2224, 2225, 22A5, 224D, 226A and 226B.
//!
//! What a format adds on top of the class stays in that format's crate: the `fence`, `separators`
//! and class markers `mt-mathml` writes on `mo`, the delimiters each markup format spells a
//! `Delim` as, and the operator spacing both formats leave to the renderer.

use crate::{Class, Font};

/// Characters that take limits when they carry scripts.
const LARGE_OPS: &str = "\u{2211}\u{220F}\u{2210}\u{22C0}\u{22C1}\u{22C2}\u{22C3}\u{2A00}\u{2A01}\u{2A02}\u{2A03}\u{2A04}\u{2A05}\u{2A06}\u{222B}\u{222C}\u{222D}\u{222E}\u{222F}\u{2230}";

const BINARY: &str = "+-*\u{2212}\u{00B1}\u{2213}\u{00D7}\u{00F7}\u{22C5}\u{2217}\u{00B7}\u{2218}\u{2216}\u{2227}\u{2228}\u{2229}\u{222A}\u{2295}\u{2296}\u{2297}\u{2299}\u{2216}";

const RELATIONS: &str = "=<>:\u{2264}\u{2265}\u{2260}\u{2248}\u{2261}\u{2208}\u{2209}\u{2282}\u{2283}\u{2286}\u{2287}\
\u{2192}\u{2190}\u{2194}\u{21D2}\u{21D4}\u{21A6}\u{2191}\u{2193}\u{27F9}\u{27FA}\u{223C}\u{221D}\u{2245}\u{225C}\
\u{2323}\u{2254}\u{2255}\u{220B}\u{2225}\u{2223}\u{2224}\u{22A5}\u{224D}\u{226A}\u{226B}\
\u{227D}";

const OPENERS: &str = "([{\u{27E8}\u{230A}\u{2308}\u{27E6}\u{301A}";
const CLOSERS: &str = ")]}\u{27E9}\u{230B}\u{2309}\u{27E7}\u{301B}";
const PUNCTUATION: &str = ",;";

/// Characters the MathType convention classes as operators or relations and the markup convention
/// leaves ordinary. The module documentation lists them by group.
const MARKUP_ORDINARY: &str = "\u{2A00}\u{2A03}\u{2A04}\u{2A05}\u{2A06}\u{2229}\u{222A}\u{2191}\u{2193}\u{2194}\u{21A6}\u{27F9}\u{27FA}\u{220B}\u{2225}\u{2223}\u{2224}\u{22A5}\u{224D}\u{226A}\u{226B}";

/// The character the markup convention spaces as a binary operator while the MathType convention
/// leaves it ordinary.
const MARKUP_BINARY: &str = "/";

/// The character the markup convention spaces as punctuation while the MathType convention
/// classes it as a relation.
const MARKUP_PUNCTUATION: &str = ":";

/// The character-classification convention a format follows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Convention {
    /// The class MathType's own output implies, which follows the TeX classes.
    MathType,
    /// The default class MathML's writer and reader share, which Office Math follows as well.
    Markup,
}

/// Whether the character is a large operator in the MathType convention.
fn is_large_op(ch: char) -> bool {
    LARGE_OPS.contains(ch)
}

/// The atom class the bare character carries in the MathType convention.
fn mathtype_class(ch: char) -> Class {
    if is_large_op(ch) {
        Class::Op
    } else if OPENERS.contains(ch) {
        Class::Open
    } else if CLOSERS.contains(ch) {
        Class::Close
    } else if PUNCTUATION.contains(ch) {
        Class::Punct
    } else if BINARY.contains(ch) {
        Class::Bin
    } else if RELATIONS.contains(ch) {
        Class::Rel
    } else {
        Class::Ord
    }
}

/// The atom class a bare character carries in the MathType convention.
///
/// A character that is not in one of the tables is an ordinary atom, so a variable and a digit
/// classify the same way.
pub fn class_of_char(ch: char) -> Class {
    class_of_char_with(ch, Convention::MathType)
}

/// The atom class a bare character carries in `convention`.
pub fn class_of_char_with(ch: char, convention: Convention) -> Class {
    match convention {
        Convention::MathType => mathtype_class(ch),
        Convention::Markup => {
            if MARKUP_ORDINARY.contains(ch) {
                Class::Ord
            } else if MARKUP_BINARY.contains(ch) {
                Class::Bin
            } else if MARKUP_PUNCTUATION.contains(ch) {
                Class::Punct
            } else {
                mathtype_class(ch)
            }
        }
    }
}

/// Whether the character takes limits when it carries scripts in `convention`.
pub fn is_large_op_with(ch: char, convention: Convention) -> bool {
    match convention {
        Convention::MathType => is_large_op(ch),
        Convention::Markup => is_large_op(ch) && !MARKUP_ORDINARY.contains(ch),
    }
}

/// Whether MathType draws the character from a symbol-encoded face: operators, relations and the
/// ordinary symbols the text face has no glyph for.
///
/// The face is the Symbol face when the Adobe Symbol encoding places the character, and the
/// extra face when the Symbol encoding does not but the MT Extra encoding does, which is where
/// MathType saves `ℓ` and `ℏ`. A character neither encoding places stays in the Symbol face
/// without a position. A relation the Euclid Math Two face places is the exception: the writer
/// takes that face, and [`euclid_math_two_position`] gives its position.
pub fn is_symbol_face(ch: char) -> bool {
    if ch.is_ascii() {
        return false;
    }
    is_large_op(ch)
        || matches!(class_of_char(ch), Class::Bin | Class::Rel)
        || matches!(
            ch,
            '\u{2200}'
                | '\u{2205}'
                | '\u{221E}'
                | '\u{2202}'
                | '\u{2207}'
                | '\u{210F}'
                | '\u{2113}'
                | '\u{2135}'
                | '\u{2118}'
                | '\u{2220}'
                | '\u{22EF}'
        )
}

/// The symbol-encoded face MathType writes `ch` in, and the position in that face.
///
/// The Symbol face comes first: MathType draws a symbol there when the Adobe Symbol encoding
/// gives it a position. A character the Symbol encoding does not place goes to the extra face at
/// the position the MT Extra encoding gives it, which is where MathType saves `ℓ` and `ℏ`.
/// Returns `None` when neither encoding places the character. A relation the Euclid Math Two
/// face places also returns `None` here: [`euclid_math_two_position`] gives the position the
/// writer and the preview take instead.
///
/// The caller asks this for a character [`is_symbol_face`] accepts. An ASCII character has a
/// position here because its own code is the position, but the text face draws it, so the face
/// returned for ASCII describes the encoding rather than the face the character is written in.
pub fn symbol_position(ch: char) -> Option<(Font, u8)> {
    symbol_code(ch)
        .map(|code| (Font::Symbol, code))
        .or_else(|| extra_code(ch).map(|code| (Font::Extra, code)))
}

/// The position MathType draws `ch` at in the Euclid Math Two face, when that face carries it.
///
/// Euclid Math Two carries relations the Symbol and MT Extra encodings do not place, at the
/// positions of its own `EuclidMath2` encoding. Its glyph `succeedsequal` at `B1` draws the
/// succeeds-or-equal relation, which MathType's AMS TeX translator spells `\succcurlyeq` for
/// MTCode `0x227D`.
pub fn euclid_math_two_position(ch: char) -> Option<u8> {
    match ch {
        '\u{227D}' => Some(0xB1),
        _ => None,
    }
}

/// The code position `ch` takes in the Symbol face's legacy encoding.
///
/// The code-to-name table of `StandardSymbolsPS.afm` gives the positions of the characters in the
/// face. MathType's Symbol face and its lower- and upper-case Greek styles draw from that font, so
/// an equation stream names a glyph's position in the character record and a preview translates
/// the character before it looks the glyph up.
///
/// The two phis are the exception. The Adobe Glyph List maps their names `phi` and `phi1` to
/// U+03C6 and U+03D5, but the face draws the straight phi `ϕ` at `66` and the loopy phi `φ` at
/// `6A`, the reverse of those names, as the face's own outlines show. MathType draws and saves by
/// position, so the table follows the drawn shapes. An ASCII character sits at its own code, which
/// the encoding does not list. Characters outside the table have no position in the encoding.
pub fn symbol_code(ch: char) -> Option<u8> {
    if ch.is_ascii() {
        return Some(ch as u8);
    }
    let index = SYMBOL_CODES
        .binary_search_by_key(&ch, |(character, _)| *character)
        .ok()?;
    Some(SYMBOL_CODES[index].1)
}

/// The code position `ch` takes in MT Extra's legacy encoding.
///
/// MT Extra holds the marks MathType's other faces lack, at the positions of the MathType Extra
/// encoding recorded in Mozilla's MathML font notes:
/// <https://www-archive.mozilla.org/projects/mathml/fonts/encoding/mtextra.html>. The notes
/// describe the reduced set Windows installs by default. The face MathType ships holds more,
/// among them the letterlike symbols MathType saves there, so the positions the face's own glyph
/// names give are in the table as well: `Rbb`, `Zbb`, `Cbb`, `Qbb` and `Nbb` sit at `A1` through
/// `A5`. Characters outside the table have no position in the encoding.
pub fn extra_code(ch: char) -> Option<u8> {
    let index = EXTRA_CODES
        .binary_search_by_key(&ch, |(character, _)| *character)
        .ok()?;
    Some(EXTRA_CODES[index].1)
}

/// The characters MT Extra places, with their positions, sorted by character.
///
/// A caller that loads the face checks it carries a glyph at each position the encoding names.
pub fn extra_positions() -> &'static [(char, u8)] {
    EXTRA_CODES
}

/// Unicode character and its code position in the Symbol font's legacy encoding.
///
/// Sorted by character, for a binary search. The documentation of [`symbol_code`] gives the
/// source.
const SYMBOL_CODES: &[(char, u8)] = &[
    ('\u{00AC}', 0xD8),
    ('\u{00B0}', 0xB0),
    ('\u{00B1}', 0xB1),
    ('\u{00B5}', 0x6D),
    ('\u{00D7}', 0xB4),
    ('\u{00F7}', 0xB8),
    ('\u{0192}', 0xA6),
    ('\u{0391}', 0x41),
    ('\u{0392}', 0x42),
    ('\u{0393}', 0x47),
    ('\u{0394}', 0x44),
    ('\u{0395}', 0x45),
    ('\u{0396}', 0x5A),
    ('\u{0397}', 0x48),
    ('\u{0398}', 0x51),
    ('\u{0399}', 0x49),
    ('\u{039A}', 0x4B),
    ('\u{039B}', 0x4C),
    ('\u{039C}', 0x4D),
    ('\u{039D}', 0x4E),
    ('\u{039E}', 0x58),
    ('\u{039F}', 0x4F),
    ('\u{03A0}', 0x50),
    ('\u{03A1}', 0x52),
    ('\u{03A3}', 0x53),
    ('\u{03A4}', 0x54),
    ('\u{03A5}', 0x55),
    ('\u{03A6}', 0x46),
    ('\u{03A7}', 0x43),
    ('\u{03A8}', 0x59),
    ('\u{03A9}', 0x57),
    ('\u{03B1}', 0x61),
    ('\u{03B2}', 0x62),
    ('\u{03B3}', 0x67),
    ('\u{03B4}', 0x64),
    ('\u{03B5}', 0x65),
    ('\u{03B6}', 0x7A),
    ('\u{03B7}', 0x68),
    ('\u{03B8}', 0x71),
    ('\u{03B9}', 0x69),
    ('\u{03BA}', 0x6B),
    ('\u{03BB}', 0x6C),
    ('\u{03BC}', 0x6D),
    ('\u{03BD}', 0x6E),
    ('\u{03BE}', 0x78),
    ('\u{03BF}', 0x6F),
    ('\u{03C0}', 0x70),
    ('\u{03C1}', 0x72),
    ('\u{03C2}', 0x56),
    ('\u{03C3}', 0x73),
    ('\u{03C4}', 0x74),
    ('\u{03C5}', 0x75),
    ('\u{03C6}', 0x6A),
    ('\u{03C7}', 0x63),
    ('\u{03C8}', 0x79),
    ('\u{03C9}', 0x77),
    ('\u{03D1}', 0x4A),
    ('\u{03D2}', 0xA1),
    ('\u{03D5}', 0x66),
    ('\u{03D6}', 0x76),
    ('\u{2022}', 0xB7),
    ('\u{2026}', 0xBC),
    ('\u{2032}', 0xA2),
    ('\u{2033}', 0xB2),
    ('\u{2044}', 0xA4),
    ('\u{20AC}', 0xA0),
    ('\u{2111}', 0xC1),
    ('\u{2118}', 0xC3),
    ('\u{211C}', 0xC2),
    ('\u{2126}', 0x57),
    ('\u{2135}', 0xC0),
    ('\u{2190}', 0xAC),
    ('\u{2191}', 0xAD),
    ('\u{2192}', 0xAE),
    ('\u{2193}', 0xAF),
    ('\u{2194}', 0xAB),
    ('\u{21B5}', 0xBF),
    ('\u{21D0}', 0xDC),
    ('\u{21D1}', 0xDD),
    ('\u{21D2}', 0xDE),
    ('\u{21D3}', 0xDF),
    ('\u{21D4}', 0xDB),
    ('\u{2200}', 0x22),
    ('\u{2202}', 0xB6),
    ('\u{2203}', 0x24),
    ('\u{2205}', 0xC6),
    ('\u{2206}', 0x44),
    ('\u{2207}', 0xD1),
    ('\u{2208}', 0xCE),
    ('\u{2209}', 0xCF),
    ('\u{220B}', 0x27),
    ('\u{220F}', 0xD5),
    ('\u{2211}', 0xE5),
    ('\u{2212}', 0x2D),
    ('\u{2217}', 0x2A),
    ('\u{221A}', 0xD6),
    ('\u{221D}', 0xB5),
    ('\u{221E}', 0xA5),
    ('\u{2220}', 0xD0),
    ('\u{2227}', 0xD9),
    ('\u{2228}', 0xDA),
    ('\u{2229}', 0xC7),
    ('\u{222A}', 0xC8),
    ('\u{222B}', 0xF2),
    ('\u{2234}', 0x5C),
    ('\u{223C}', 0x7E),
    ('\u{2245}', 0x40),
    ('\u{2248}', 0xBB),
    ('\u{2260}', 0xB9),
    ('\u{2261}', 0xBA),
    ('\u{2264}', 0xA3),
    ('\u{2265}', 0xB3),
    ('\u{2282}', 0xCC),
    ('\u{2283}', 0xC9),
    ('\u{2284}', 0xCB),
    ('\u{2286}', 0xCD),
    ('\u{2287}', 0xCA),
    ('\u{2295}', 0xC5),
    ('\u{2297}', 0xC4),
    ('\u{22A5}', 0x5E),
    ('\u{22C5}', 0xD7),
    ('\u{2320}', 0xF3),
    ('\u{2321}', 0xF5),
    ('\u{2329}', 0xE1),
    ('\u{232A}', 0xF1),
    ('\u{25CA}', 0xE0),
    ('\u{2660}', 0xAA),
    ('\u{2663}', 0xA7),
    ('\u{2665}', 0xA9),
    ('\u{2666}', 0xA8),
];

/// Unicode character and its code position in MT Extra's legacy encoding.
///
/// Sorted by character, for a binary search. The documentation of [`extra_code`] gives the
/// source.
const EXTRA_CODES: &[(char, u8)] = &[
    ('\u{019B}', 0x44),
    ('\u{0300}', 0x23),
    ('\u{0302}', 0x24),
    ('\u{0303}', 0x25),
    ('\u{0307}', 0x26),
    ('\u{2026}', 0x4B),
    ('\u{2035}', 0x60),
    ('\u{20D0}', 0x77),
    ('\u{20D1}', 0x76),
    ('\u{20D6}', 0x73),
    ('\u{20D7}', 0x72),
    ('\u{20E1}', 0x74),
    ('\u{2102}', 0xA3),
    ('\u{210F}', 0x68),
    ('\u{2113}', 0x6C),
    ('\u{2115}', 0xA5),
    ('\u{211A}', 0xA4),
    ('\u{211D}', 0xA1),
    ('\u{2124}', 0xA2),
    ('\u{2195}', 0x62),
    ('\u{21A6}', 0x61),
    ('\u{21D5}', 0x63),
    ('\u{2210}', 0x43),
    ('\u{2213}', 0x6D),
    ('\u{2218}', 0x6F),
    ('\u{2229}', 0x49),
    ('\u{222A}', 0x55),
    ('\u{2235}', 0x51),
    ('\u{225C}', 0x40),
    ('\u{227A}', 0x70),
    ('\u{227B}', 0x66),
    ('\u{22C2}', 0x49),
    ('\u{22C3}', 0x55),
    ('\u{22EE}', 0x4D),
    ('\u{22EF}', 0x4C),
    ('\u{22F0}', 0x4E),
    ('\u{22F1}', 0x4F),
    ('\u{25B9}', 0x3E),
    ('\u{25C3}', 0x3C),
    ('\u{FE36}', 0x7B),
    ('\u{FE38}', 0x7D),
];

/// Whether MathType draws the character from the CJK face.
///
/// The CJK face covers the writing systems of Chinese, Japanese and Korean: their punctuation,
/// kana and ideographs, including the compatibility and extension blocks. MathType declares that
/// face in every stream it writes and selects it with typeface 12.
pub fn is_cjk(ch: char) -> bool {
    matches!(
        ch as u32,
        0x1100..=0x11FF      // hangul jamo
        | 0x2E80..=0x2FDF    // CJK radicals and Kangxi radicals
        | 0x2FF0..=0x2FFF    // ideographic description characters
        | 0x3000..=0x30FF    // CJK punctuation, hiragana and katakana
        | 0x3100..=0x312F    // bopomofo
        | 0x3130..=0x318F    // hangul compatibility jamo
        | 0x3190..=0x319F    // kanbun
        | 0x31A0..=0x31BF    // bopomofo extended
        | 0x31C0..=0x31EF    // CJK strokes
        | 0x31F0..=0x31FF    // katakana phonetic extensions
        | 0x3200..=0x33FF    // enclosed CJK letters and months, compatibility
        | 0x3400..=0x4DBF    // CJK unified ideographs extension A
        | 0x4E00..=0x9FFF    // CJK unified ideographs
        | 0xA960..=0xA97F    // hangul jamo extended-A
        | 0xAC00..=0xD7AF    // hangul syllables
        | 0xD7B0..=0xD7FF    // hangul jamo extended-B
        | 0xF900..=0xFAFF    // CJK compatibility ideographs
        | 0xFE10..=0xFE1F    // vertical forms
        | 0xFE30..=0xFE4F    // CJK compatibility forms
        | 0xFE50..=0xFE6F    // small form variants
        | 0xFF00..=0xFFEF    // halfwidth and fullwidth forms
        | 0x1B000..=0x1B16F  // kana supplement and extended
        | 0x1F200..=0x1F2FF  // enclosed ideographic supplement
        | 0x20000..=0x3FFFF  // CJK unified ideographs extensions B and later
    )
}

/// Letterlike symbols in the BMP, with the letter and face each one stands for.
///
/// MathType spells a styled letter whose Unicode block has a BMP character as that character, in
/// the face its standard faces do not cover, i.e. the extra face. A tree keeps the plain letter in
/// the styled face instead, so this table is the way between the two: the reader recovers the
/// letter and face from the saved character, the writer recovers the saved character from them,
/// and the preview asks which characters MathType saved in the extra face at all.
///
/// Sorted by character, for a binary search.
const EXTRA_LETTERS: [(char, char, Font); 23] = [
    ('\u{2102}', 'C', Font::DoubleStruck),
    ('\u{210A}', 'g', Font::Script),
    ('\u{210B}', 'H', Font::Script),
    ('\u{210C}', 'H', Font::Fraktur),
    ('\u{210D}', 'H', Font::DoubleStruck),
    ('\u{2110}', 'I', Font::Script),
    ('\u{2111}', 'I', Font::Fraktur),
    ('\u{2112}', 'L', Font::Script),
    ('\u{2115}', 'N', Font::DoubleStruck),
    ('\u{2119}', 'P', Font::DoubleStruck),
    ('\u{211A}', 'Q', Font::DoubleStruck),
    ('\u{211B}', 'R', Font::Script),
    ('\u{211C}', 'R', Font::Fraktur),
    ('\u{211D}', 'R', Font::DoubleStruck),
    ('\u{2124}', 'Z', Font::DoubleStruck),
    ('\u{2128}', 'Z', Font::Fraktur),
    ('\u{212C}', 'B', Font::Script),
    ('\u{212D}', 'C', Font::Fraktur),
    ('\u{212F}', 'e', Font::Script),
    ('\u{2130}', 'E', Font::Script),
    ('\u{2131}', 'F', Font::Script),
    ('\u{2133}', 'M', Font::Script),
    ('\u{2134}', 'o', Font::Script),
];

/// The letter and face a letterlike symbol in the BMP stands for.
pub fn extra_letter(ch: char) -> Option<(char, Font)> {
    let index = EXTRA_LETTERS
        .binary_search_by_key(&ch, |(symbol, _, _)| *symbol)
        .ok()?;
    let (_, letter, font) = EXTRA_LETTERS[index];
    Some((letter, font))
}

/// The letterlike symbol in the BMP MathType saves a styled letter as, when Unicode has one.
pub fn extra_symbol(letter: char, font: Font) -> Option<char> {
    EXTRA_LETTERS
        .iter()
        .find(|(_, saved, face)| *saved == letter && *face == font)
        .map(|(symbol, _, _)| *symbol)
}

/// Whether MathType saves the character in the extra face.
pub fn is_extra_face(ch: char) -> bool {
    extra_letter(ch).is_some()
}

#[cfg(test)]
mod tests {
    use super::{
        Convention, class_of_char, class_of_char_with, extra_code, is_cjk, is_large_op_with,
        is_symbol_face, symbol_code, symbol_position,
    };
    use crate::{Class, Font};

    #[test]
    fn cjk_letters_and_punctuation_take_the_cjk_face() {
        for ch in [
            '\u{4E3A}',
            '\u{4E2D}',
            '\u{3001}',
            '\u{3002}',
            '\u{300C}',
            '\u{3042}',
            '\u{30A2}',
            '\u{2FF0}',
            '\u{31B0}',
            '\u{31F0}',
            '\u{FF08}',
            '\u{FF11}',
            '\u{FA0E}',
            '\u{1B000}',
            '\u{1F200}',
            '\u{20000}',
            '\u{1100}',
            '\u{3131}',
            '\u{AC00}',
            '\u{3190}',
            '\u{FE10}',
            '\u{FE50}',
        ] {
            assert!(is_cjk(ch), "{ch:?} is drawn from the CJK face");
        }
    }

    #[test]
    fn latin_letters_greek_and_math_symbols_stay_out_of_the_cjk_face() {
        for ch in [
            'A', 'x', '0', '\u{03B1}', '\u{2211}', '\u{2192}', '\u{00E9}',
        ] {
            assert!(!is_cjk(ch), "{ch:?} is not drawn from the CJK face");
        }
    }

    #[test]
    fn operators_relations_and_large_operators_take_the_symbol_face() {
        for ch in [
            '\u{2212}', '\u{2211}', '\u{2208}', '\u{2264}', '\u{00B1}', '\u{00D7}', '\u{222B}',
            '\u{220F}',
        ] {
            assert!(is_symbol_face(ch), "{ch:?} is drawn from the Symbol face");
        }
    }

    #[test]
    fn ordinary_symbols_the_text_face_lacks_take_the_symbol_face() {
        for ch in ['\u{2205}', '\u{221E}', '\u{2202}', '\u{2207}', '\u{2200}'] {
            assert!(is_symbol_face(ch), "{ch:?} is drawn from the Symbol face");
        }
    }

    #[test]
    fn ascii_and_variable_letters_stay_in_the_text_face() {
        for ch in [
            '-', '+', '=', 'x', 'A', '0', '\u{03B1}', '\u{03C6}', '\u{221A}',
        ] {
            assert!(!is_symbol_face(ch), "{ch:?} is drawn from the text face");
        }
    }

    #[test]
    fn the_symbol_table_names_the_legacy_positions() {
        assert_eq!(symbol_code('A'), Some(0x41));
        assert_eq!(symbol_code('\u{03B1}'), Some(0x61));
        assert_eq!(symbol_code('\u{0394}'), Some(0x44));
        assert_eq!(symbol_code('\u{03BC}'), Some(0x6D));
        assert_eq!(symbol_code('\u{03A9}'), Some(0x57));
        assert_eq!(symbol_code('\u{03C2}'), Some(0x56));
        assert_eq!(
            symbol_code('\u{03C6}'),
            Some(0x6A),
            "the loopy phi takes the position the Symbol font draws it at"
        );
        assert_eq!(
            symbol_code('\u{03D5}'),
            Some(0x66),
            "the straight phi takes the position the Symbol font draws it at"
        );
        assert_eq!(symbol_code('\u{2211}'), Some(0xE5));
        assert_eq!(symbol_code('\u{222B}'), Some(0xF2));
        assert_eq!(symbol_code('\u{2264}'), Some(0xA3));
        assert_eq!(symbol_code('\u{1D465}'), None);
    }

    #[test]
    fn a_bare_character_classifies_by_the_latex_conventions() {
        assert_eq!(class_of_char('\u{2211}'), Class::Op);
        assert_eq!(class_of_char('\u{2212}'), Class::Bin);
        assert_eq!(class_of_char('\u{2208}'), Class::Rel);
        assert_eq!(class_of_char('('), Class::Open);
        assert_eq!(class_of_char(']'), Class::Close);
        assert_eq!(class_of_char(','), Class::Punct);
        assert_eq!(class_of_char('x'), Class::Ord);
        assert_eq!(class_of_char('0'), Class::Ord);
    }

    #[test]
    fn the_succeeds_or_equal_relation_is_a_relation() {
        assert_eq!(class_of_char('\u{227D}'), Class::Rel);
        assert!(
            is_symbol_face('\u{227D}'),
            "MathType draws the relation from a face other than the text face"
        );
    }

    #[test]
    fn the_euclid_math_two_encoding_names_the_succeeds_or_equal_position() {
        use super::euclid_math_two_position;
        assert_eq!(euclid_math_two_position('\u{227D}'), Some(0xB1));
        assert_eq!(euclid_math_two_position('\u{227C}'), None);
        assert_eq!(euclid_math_two_position('Q'), None);
    }

    #[test]
    fn the_markup_convention_takes_the_slash_as_binary_and_the_colon_as_punctuation() {
        assert_eq!(class_of_char_with('/', Convention::MathType), Class::Ord);
        assert_eq!(class_of_char_with('/', Convention::Markup), Class::Bin);
        assert_eq!(class_of_char_with(':', Convention::MathType), Class::Rel);
        assert_eq!(class_of_char_with(':', Convention::Markup), Class::Punct);
    }

    #[test]
    fn the_markup_convention_leaves_the_arrows_and_the_extra_relations_ordinary() {
        for ch in [
            '\u{2191}', '\u{2193}', '\u{2194}', '\u{21A6}', '\u{27F9}', '\u{27FA}', '\u{220B}',
            '\u{2225}', '\u{2223}', '\u{2224}', '\u{22A5}', '\u{224D}', '\u{226A}', '\u{226B}',
        ] {
            assert_eq!(class_of_char_with(ch, Convention::MathType), Class::Rel);
            assert_eq!(
                class_of_char_with(ch, Convention::Markup),
                Class::Ord,
                "{ch:?} is ordinary in the markup convention"
            );
        }
    }

    #[test]
    fn the_markup_convention_leaves_the_union_intersection_and_the_circled_operators_ordinary() {
        for ch in ['\u{2229}', '\u{222A}'] {
            assert_eq!(class_of_char_with(ch, Convention::MathType), Class::Bin);
            assert_eq!(class_of_char_with(ch, Convention::Markup), Class::Ord);
        }
        for ch in ['\u{2A00}', '\u{2A03}', '\u{2A04}', '\u{2A05}', '\u{2A06}'] {
            assert!(is_large_op_with(ch, Convention::MathType), "{ch:?}");
            assert!(!is_large_op_with(ch, Convention::Markup), "{ch:?}");
            assert_eq!(class_of_char_with(ch, Convention::Markup), Class::Ord);
        }
    }

    #[test]
    fn both_conventions_agree_on_the_shared_operators_and_the_delimiters() {
        for ch in [
            '\u{2211}', '\u{220F}', '\u{2210}', '\u{222B}', '\u{2230}', '\u{22C0}', '\u{22C1}',
            '\u{22C2}', '\u{22C3}', '\u{2A01}', '\u{2A02}',
        ] {
            assert!(is_large_op_with(ch, Convention::MathType), "{ch:?}");
            assert!(is_large_op_with(ch, Convention::Markup), "{ch:?}");
        }
        for (ch, class) in [
            ('(', Class::Open),
            (')', Class::Close),
            ('[', Class::Open),
            (']', Class::Close),
            ('{', Class::Open),
            ('}', Class::Close),
            ('\u{27E8}', Class::Open),
            ('\u{27E9}', Class::Close),
            ('+', Class::Bin),
            ('=', Class::Rel),
            (',', Class::Punct),
            (';', Class::Punct),
            ('x', Class::Ord),
            ('0', Class::Ord),
        ] {
            assert_eq!(class_of_char_with(ch, Convention::MathType), class);
            assert_eq!(class_of_char_with(ch, Convention::Markup), class);
        }
    }

    #[test]
    fn the_letterlike_table_is_sorted_for_the_binary_search() {
        assert!(
            super::EXTRA_LETTERS
                .windows(2)
                .all(|pair| pair[0].0 < pair[1].0),
            "the table is searched by character, so it must stay sorted"
        );
    }

    #[test]
    fn letterlike_symbols_name_the_letter_and_face_math_type_saved_them_for() {
        use super::extra_letter;
        assert_eq!(
            extra_letter('\u{211D}'),
            Some(('R', crate::Font::DoubleStruck))
        );
        assert_eq!(extra_letter('\u{212C}'), Some(('B', crate::Font::Script)));
        assert_eq!(extra_letter('\u{212D}'), Some(('C', crate::Font::Fraktur)));
        assert_eq!(extra_letter('R'), None);
        assert_eq!(
            extra_letter('\u{1D54D}'),
            None,
            "the block has no BMP character"
        );
    }

    #[test]
    fn the_extra_face_covers_the_letterlike_symbols_in_the_bmp() {
        use super::is_extra_face;
        for ch in ['\u{211D}', '\u{212C}', '\u{212D}', '\u{2102}', '\u{2134}'] {
            assert!(is_extra_face(ch), "{ch:?} is saved in the extra face");
        }
        for ch in ['R', '\u{1D54D}', '\u{2113}', '\u{210F}'] {
            assert!(!is_extra_face(ch), "{ch:?} is not saved in the extra face");
        }
    }

    #[test]
    fn the_symbol_encoding_names_the_legacy_positions() {
        assert_eq!(symbol_code('\u{03B1}'), Some(0x61));
        assert_eq!(symbol_code('\u{0394}'), Some(0x44));
        assert_eq!(symbol_code('\u{03BC}'), Some(0x6D));
        assert_eq!(symbol_code('\u{03A9}'), Some(0x57));
        assert_eq!(symbol_code('\u{03C2}'), Some(0x56));
        assert_eq!(symbol_code('\u{2211}'), Some(0xE5));
        assert_eq!(symbol_code('\u{222B}'), Some(0xF2));
        assert_eq!(symbol_code('\u{2264}'), Some(0xA3));
        assert_eq!(symbol_code('A'), Some(0x41), "ASCII sits at its own code");
        assert_eq!(symbol_code('\u{1D465}'), None);
    }

    #[test]
    fn the_extra_encoding_names_the_math_type_positions() {
        assert_eq!(extra_code('\u{019B}'), Some(0x44));
        assert_eq!(extra_code('\u{2113}'), Some(0x6C));
        assert_eq!(extra_code('\u{210F}'), Some(0x68));
        assert_eq!(extra_code('\u{2213}'), Some(0x6D));
        assert_eq!(extra_code('\u{20D7}'), Some(0x72));
        assert_eq!(extra_code('\u{211D}'), Some(0xA1));
        assert_eq!(extra_code('\u{2115}'), Some(0xA5));
        assert_eq!(extra_code('\u{22C3}'), Some(0x55));
        assert_eq!(extra_code('\u{22C2}'), Some(0x49));
        assert_eq!(extra_code('\u{225C}'), Some(0x40));
        assert_eq!(extra_code('\u{22EF}'), Some(0x4C));
        assert_eq!(extra_code('\u{212C}'), None, "the face has no script B");
        assert_eq!(extra_code('\u{1D465}'), None);
    }

    #[test]
    fn a_symbol_takes_the_symbol_face_unless_only_the_extra_encoding_places_it() {
        assert_eq!(symbol_position('\u{2211}'), Some((Font::Symbol, 0xE5)));
        assert_eq!(symbol_position('\u{2229}'), Some((Font::Symbol, 0xC7)));
        assert_eq!(symbol_position('\u{2113}'), Some((Font::Extra, 0x6C)));
        assert_eq!(symbol_position('\u{210F}'), Some((Font::Extra, 0x68)));
        assert_eq!(symbol_position('\u{2213}'), Some((Font::Extra, 0x6D)));
        assert_eq!(symbol_position('\u{22C3}'), Some((Font::Extra, 0x55)));
        assert_eq!(symbol_position('\u{22C2}'), Some((Font::Extra, 0x49)));
        assert_eq!(symbol_position('\u{225C}'), Some((Font::Extra, 0x40)));
        assert_eq!(symbol_position('\u{22EF}'), Some((Font::Extra, 0x4C)));
        assert_eq!(
            symbol_position('\u{222A}'),
            Some((Font::Symbol, 0xC8)),
            "a character the Symbol encoding places stays in that face"
        );
        assert_eq!(symbol_position('\u{2225}'), None);
    }
}