mathtex-editor-keymap 0.1.0

Pluggable Hypatia style default keymap for mathtex-editor, translating input into core commands
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
//! The default Hypatia keymap maps host input to primitive `Command`s.
#![allow(dead_code)]

use std::collections::HashMap;

use mathtex_editor_core::command::{Command, Dir};
use mathtex_editor_core::model::{FracStyle, MathClass, MatrixEnv, ScriptSlot, Symbol};

/// A normalized key event from the host matching browser `KeyboardEvent` fields.
#[derive(Debug, Clone)]
pub struct KeyInput {
    /// The `KeyboardEvent.key` value such as `"a"`, `"/"`, `"ArrowLeft"`, or `"Backspace"`.
    pub key: String,
    /// Whether the shift modifier is active.
    pub shift: bool,
    /// Whether the control modifier is active.
    pub ctrl: bool,
    /// Whether the alt modifier is active.
    pub alt: bool,
    /// Whether the meta modifier is active.
    pub meta: bool,
}

/// Input state for character autocorrect, word autoconvert, and host word shortcuts.
#[derive(Debug, Default)]
pub struct Keymap {
    last_char: Option<char>,
    word: String,
    word_overrides: HashMap<String, Vec<Command>>,
}

impl Keymap {
    /// Create an empty keymap with the built in shortcuts.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a user word shortcut so `word` plus space expands to `commands`.
    pub fn define_word(&mut self, word: impl Into<String>, commands: Vec<Command>) {
        self.word_overrides.insert(word.into(), commands);
    }

    /// Remove a previously registered word shortcut while leaving built ins unaffected.
    pub fn undefine_word(&mut self, word: &str) {
        self.word_overrides.remove(word);
    }

    /// Return words the keymap can expand for a `\` command popover.
    pub fn entries(&self) -> Vec<KeymapEntry<'_>> {
        let mut out: Vec<KeymapEntry<'_>> = Vec::new();
        for w in self.word_overrides.keys() {
            out.push(KeymapEntry { word: w.as_str(), label: w.as_str() });
        }
        for s in CATALOG {
            if !self.word_overrides.contains_key(s.word) {
                out.push(KeymapEntry { word: s.word, label: s.label });
            }
        }
        for &op in OPERATORS {
            if !self.word_overrides.contains_key(op) {
                out.push(KeymapEntry { word: op, label: op });
            }
        }
        out
    }

    /// Translate a key event into zero or more editor commands.
    pub fn map_key(&mut self, input: &KeyInput) -> Vec<Command> {
        let named = match input.key.as_str() {
            "ArrowLeft" => Some(dir_cmd(Dir::Left, input.shift)),
            "ArrowRight" => Some(dir_cmd(Dir::Right, input.shift)),
            "ArrowUp" => Some(dir_cmd(Dir::Up, input.shift)),
            "ArrowDown" => Some(dir_cmd(Dir::Down, input.shift)),
            "Home" => Some(Command::MoveLineStart),
            "End" => Some(Command::MoveLineEnd),
            "Tab" => Some(if input.shift {
                Command::ShiftTab
            } else {
                Command::Tab
            }),
            "Backspace" => Some(Command::DeleteBackward),
            "Delete" => Some(Command::DeleteForward),
            // Enter confirms a pending Backspace swap menu or behaves like Collapse.
            "Enter" => Some(Command::Confirm),
            "Escape" => Some(Command::Collapse), // host decides; reset state
            _ => None,
        };
        if let Some(cmd) = named {
            self.reset();
            return if matches!(cmd, Command::Collapse) {
                vec![cmd] // benign reset, host may also act
            } else {
                vec![cmd]
            };
        }

        if input.ctrl || input.meta {
            self.reset();
            return match input.key.as_str() {
                "a" | "A" => vec![Command::SelectAll],
                _ => vec![],
            };
        }

        match single_char(&input.key) {
            Some(ch) => self.map_char(ch),
            None => vec![],
        }
    }

    /// Translate committed text by replaying it through `map_char` one character at a time.
    pub fn map_text(&mut self, text: &str) -> Vec<Command> {
        self.reset();
        text.chars().flat_map(|ch| self.map_char(ch)).collect()
    }

    fn reset(&mut self) {
        self.last_char = None;
        self.word.clear();
    }

    fn map_char(&mut self, ch: char) -> Vec<Command> {
        // Space converts the preceding word or is swallowed.
        if ch == ' ' {
            return self.flush_word();
        }
        // Two character symbol autocorrect.
        if let Some(prev) = self.last_char {
            if let Some(repl) = two_char(prev, ch) {
                self.reset();
                return vec![Command::DeleteBackward, insert(repl)];
            }
        }
        self.last_char = Some(ch);
        if ch.is_ascii_alphabetic() {
            self.word.push(ch);
        } else {
            self.word.clear();
        }
        match ch {
            '/' => vec![Command::InsertFraction(FracStyle::Bar)],
            '^' => vec![Command::InsertScript(ScriptSlot::Sup)],
            '_' => vec![Command::InsertScript(ScriptSlot::Sub)],
            '(' => vec![delims('(', ')')],
            '[' => vec![delims('[', ']')],
            '{' => vec![delims('{', '}')],
            '|' => vec![delims('|', '|')],
            '\'' => vec![Command::InsertScript(ScriptSlot::Sup), insert("\\prime")],
            '*' => vec![insert("\\cdot")],
            c => vec![Command::InsertAtom(atom(c))],
        }
    }

    /// Convert the buffered word on space or swallow the space if the word is unknown.
    fn flush_word(&mut self) -> Vec<Command> {
        self.last_char = None;
        let word = std::mem::take(&mut self.word);
        if word.is_empty() {
            return vec![];
        }
        match self.lookup(&word) {
            Some(mut cmds) => {
                let mut out = vec![Command::DeleteBackward; word.chars().count()];
                out.append(&mut cmds);
                out
            }
            None => vec![],
        }
    }

    /// Resolve a word using host overrides, catalog entries, then upright operators.
    fn lookup(&self, word: &str) -> Option<Vec<Command>> {
        if let Some(cmds) = self.word_overrides.get(word) {
            return Some(cmds.clone());
        }
        if let Some(s) = CATALOG.iter().find(|s| s.word == word) {
            return Some(s.insert.commands());
        }
        if OPERATORS.contains(&word) {
            return Some(vec![named_atom(&format!("\\{word}"))]);
        }
        None
    }

    /// Resolve a word directly for a host rendered `\` command palette.
    pub fn commands_for_word(&self, word: &str) -> Option<Vec<Command>> {
        self.lookup(word)
    }
}

/// The insertion shape shared by catalog entries.
#[derive(Debug, Clone, Copy)]
enum Insertion {
    /// A named atom whose class comes from [`class_of_latex`].
    Symbol(&'static str),
    Fraction(FracStyle),
    Root,
    /// A big operator with stacked limit slots.
    BigOperator(&'static str),
    /// A matrix like environment with a fixed `rows` x `cols` grid.
    Matrix(MatrixEnv, usize, usize),
}

impl Insertion {
    fn commands(self) -> Vec<Command> {
        match self {
            Insertion::Symbol(latex) => vec![named_atom(latex)],
            Insertion::Fraction(style) => vec![Command::InsertFraction(style)],
            Insertion::Root => vec![Command::InsertSqrt],
            Insertion::BigOperator(latex) => vec![Command::InsertBigOp(Symbol {
                latex: latex.to_string(),
                class: MathClass::Op,
            })],
            Insertion::Matrix(env, rows, cols) => vec![Command::InsertMatrix { env, rows, cols }],
        }
    }
}

/// One catalog row with a trigger word, display label, and insertion.
#[derive(Debug, Clone, Copy)]
struct Shortcut {
    word: &'static str,
    label: &'static str,
    insert: Insertion,
}

/// A popover row with a trigger word and display label.
#[derive(Debug, Clone, Copy)]
pub struct KeymapEntry<'a> {
    /// The shortcut trigger word.
    pub word: &'a str,
    /// The label shown for the shortcut.
    pub label: &'a str,
}

/// Terse constructor for a plain named symbol entry whose label defaults to the word.
const fn sym(word: &'static str, latex: &'static str) -> Shortcut {
    Shortcut { word, label: word, insert: Insertion::Symbol(latex) }
}

/// Terse constructor for a big operator entry whose label defaults to the word.
const fn bigop(word: &'static str, latex: &'static str) -> Shortcut {
    Shortcut { word, label: word, insert: Insertion::BigOperator(latex) }
}

/// The built in word to insertion catalog for structures, big operators, and named symbols.
const CATALOG: &[Shortcut] = &[
    // structures
    Shortcut { word: "frac", label: "fraction", insert: Insertion::Fraction(FracStyle::Bar) },
    Shortcut { word: "dfrac", label: "display fraction", insert: Insertion::Fraction(FracStyle::Display) },
    Shortcut { word: "binom", label: "binomial", insert: Insertion::Fraction(FracStyle::Binom) },
    Shortcut { word: "sqrt", label: "square root", insert: Insertion::Root },
    Shortcut { word: "root", label: "root", insert: Insertion::Root },
    // big operators with stacked limits
    bigop("sum", "\\sum"),
    bigop("prod", "\\prod"),
    bigop("coprod", "\\coprod"),
    bigop("int", "\\int"),
    bigop("iint", "\\iint"),
    bigop("iiint", "\\iiint"),
    bigop("oint", "\\oint"),
    bigop("bigcup", "\\bigcup"),
    bigop("bigcap", "\\bigcap"),
    bigop("bigsqcup", "\\bigsqcup"),
    bigop("biguplus", "\\biguplus"),
    bigop("bigoplus", "\\bigoplus"),
    bigop("bigotimes", "\\bigotimes"),
    bigop("bigodot", "\\bigodot"),
    bigop("bigvee", "\\bigvee"),
    bigop("bigwedge", "\\bigwedge"),
    // matrices
    Shortcut { word: "pmatrix", label: "matrix (parentheses)", insert: Insertion::Matrix(MatrixEnv::Pmatrix, 2, 2) },
    Shortcut { word: "bmatrix", label: "matrix (brackets)", insert: Insertion::Matrix(MatrixEnv::Bmatrix, 2, 2) },
    Shortcut { word: "vmatrix", label: "matrix (bars / determinant)", insert: Insertion::Matrix(MatrixEnv::Vmatrix, 2, 2) },
    Shortcut { word: "matrix", label: "matrix (plain)", insert: Insertion::Matrix(MatrixEnv::Matrix, 2, 2) },
    Shortcut { word: "cases", label: "cases", insert: Insertion::Matrix(MatrixEnv::Cases, 2, 2) },
    Shortcut { word: "aligned", label: "aligned equations", insert: Insertion::Matrix(MatrixEnv::Aligned, 2, 2) },
    Shortcut { word: "align", label: "aligned equations", insert: Insertion::Matrix(MatrixEnv::Aligned, 2, 2) },
    Shortcut { word: "array", label: "array", insert: Insertion::Matrix(MatrixEnv::Array, 2, 2) },
    // lower greek
    sym("alpha", "\\alpha"),
    sym("beta", "\\beta"),
    sym("gamma", "\\gamma"),
    sym("delta", "\\delta"),
    sym("epsilon", "\\epsilon"),
    sym("varepsilon", "\\varepsilon"),
    sym("zeta", "\\zeta"),
    sym("eta", "\\eta"),
    sym("theta", "\\theta"),
    sym("vartheta", "\\vartheta"),
    sym("iota", "\\iota"),
    sym("kappa", "\\kappa"),
    sym("lambda", "\\lambda"),
    sym("mu", "\\mu"),
    sym("nu", "\\nu"),
    sym("xi", "\\xi"),
    sym("pi", "\\pi"),
    sym("rho", "\\rho"),
    sym("sigma", "\\sigma"),
    sym("tau", "\\tau"),
    sym("upsilon", "\\upsilon"),
    sym("phi", "\\phi"),
    sym("varphi", "\\varphi"),
    sym("chi", "\\chi"),
    sym("psi", "\\psi"),
    sym("omega", "\\omega"),
    // upper greek
    sym("Gamma", "\\Gamma"),
    sym("Delta", "\\Delta"),
    sym("Theta", "\\Theta"),
    sym("Lambda", "\\Lambda"),
    sym("Xi", "\\Xi"),
    sym("Pi", "\\Pi"),
    sym("Sigma", "\\Sigma"),
    sym("Phi", "\\Phi"),
    sym("Psi", "\\Psi"),
    sym("Omega", "\\Omega"),
    // calculus and misc symbols
    sym("infty", "\\infty"),
    sym("infinity", "\\infty"),
    sym("partial", "\\partial"),
    sym("nabla", "\\nabla"),
    // The differential is upright `\mathrm{d}` for integrals and derivatives.
    Shortcut { word: "dd", label: "differential", insert: Insertion::Symbol("\\mathrm{d}") },
    // binary operators and relations
    sym("pm", "\\pm"),
    sym("mp", "\\mp"),
    sym("times", "\\times"),
    sym("div", "\\div"),
    sym("cdot", "\\cdot"),
    sym("ast", "\\ast"),
    sym("star", "\\star"),
    sym("leq", "\\leq"),
    sym("le", "\\leq"),
    sym("geq", "\\geq"),
    sym("ge", "\\geq"),
    sym("neq", "\\neq"),
    sym("ne", "\\neq"),
    sym("approx", "\\approx"),
    sym("equiv", "\\equiv"),
    sym("cong", "\\cong"),
    sym("sim", "\\sim"),
    sym("propto", "\\propto"),
    sym("to", "\\to"),
    sym("gets", "\\gets"),
    sym("implies", "\\implies"),
    sym("iff", "\\iff"),
    // sets and logic
    sym("in", "\\in"),
    sym("notin", "\\notin"),
    sym("subset", "\\subset"),
    sym("subseteq", "\\subseteq"),
    sym("supset", "\\supset"),
    sym("cup", "\\cup"),
    sym("cap", "\\cap"),
    sym("emptyset", "\\emptyset"),
    sym("forall", "\\forall"),
    sym("exists", "\\exists"),
    sym("neg", "\\neg"),
    sym("land", "\\land"),
    sym("lor", "\\lor"),
    // dots, arrows, and misc symbols
    sym("cdots", "\\cdots"),
    sym("ldots", "\\ldots"),
    sym("dots", "\\dots"),
    sym("rightarrow", "\\rightarrow"),
    sym("leftarrow", "\\leftarrow"),
    sym("angle", "\\angle"),
    sym("perp", "\\perp"),
    sym("parallel", "\\parallel"),
];

fn dir_cmd(dir: Dir, shift: bool) -> Command {
    if shift {
        Command::Extend(dir)
    } else {
        Command::Move(dir)
    }
}

fn delims(open: char, close: char) -> Command {
    Command::InsertDelimiters { open, close }
}

fn single_char(key: &str) -> Option<char> {
    let mut it = key.chars();
    match (it.next(), it.next()) {
        (Some(c), None) => Some(c),
        _ => None,
    }
}

fn atom(c: char) -> Symbol {
    Symbol::from_char(c) // escapes TeX specials like %, $, ~, and \
}

fn insert(latex: &str) -> Command {
    Command::InsertAtom(Symbol {
        latex: latex.to_string(),
        class: class_of_latex(latex),
    })
}

fn named_atom(latex: &str) -> Command {
    insert(latex)
}

fn class_of_latex(latex: &str) -> MathClass {
    if let Some(name) = latex.strip_prefix('\\') {
        if OPERATORS.contains(&name) {
            return MathClass::Op;
        }
    }
    match latex {
        "\\leq" | "\\geq" | "\\neq" | "\\equiv" | "\\approx" | "\\cong" | "\\to" | "\\sim"
        | "\\implies" | "\\iff" | "\\gets" | "\\propto" | "\\in" | "\\notin" | "\\subset"
        | "\\subseteq" | "\\supset" | "\\rightarrow" | "\\leftarrow" | "\\Rightarrow"
        | "\\Leftarrow" | "\\perp" | "\\parallel" => MathClass::Rel,
        "\\pm" | "\\mp" | "\\times" | "\\div" | "\\cdot" | "\\ast" | "\\star" | "\\cup"
        | "\\cap" => MathClass::Bin,
        _ => MathClass::Ord,
    }
}

/// The Hypatia two character autoconvert table.
fn two_char(a: char, b: char) -> Option<&'static str> {
    Some(match (a, b) {
        ('<', '=') => "\\leq",
        ('>', '=') => "\\geq",
        ('!', '=') => "\\neq",
        ('=', '=') => "\\equiv",
        ('=', '~') => "\\cong",
        ('~', '~') => "\\approx",
        ('-', '>') => "\\to",
        ('<', '-') => "\\gets",
        ('=', '>') => "\\implies",
        ('+', '-') => "\\pm",
        ('-', '+') => "\\mp",
        (':', '-') => "\\div",
        ('<', '<') => "\\langle",
        ('>', '>') => "\\rangle",
        _ => return None,
    })
}

/// Named operators that render upright and feed word lookup.
const OPERATORS: &[&str] = &[
    "sin", "cos", "tan", "cot", "sec", "csc", "sinh", "cosh", "tanh", "arcsin", "arccos", "arctan",
    "log", "ln", "exp", "lim", "max", "min", "sup", "inf", "gcd", "det", "dim", "ker", "arg", "deg",
    "hom",
];

#[cfg(test)]
mod tests {
    use super::*;
    use mathtex_editor_core::model::MatrixEnv;

    fn k(key: &str) -> KeyInput {
        KeyInput {
            key: key.into(),
            shift: false,
            ctrl: false,
            alt: false,
            meta: false,
        }
    }

    fn sym(latex: &str, class: MathClass) -> Command {
        Command::InsertAtom(Symbol {
            latex: latex.into(),
            class,
        })
    }

    #[test]
    fn arrows_and_shift() {
        let mut km = Keymap::new();
        assert_eq!(km.map_key(&k("ArrowLeft")), vec![Command::Move(Dir::Left)]);
        let mut shifted = k("ArrowRight");
        shifted.shift = true;
        assert_eq!(km.map_key(&shifted), vec![Command::Extend(Dir::Right)]);
    }

    #[test]
    fn structure_keys() {
        let mut km = Keymap::new();
        assert_eq!(
            km.map_key(&k("/")),
            vec![Command::InsertFraction(FracStyle::Bar)]
        );
        assert_eq!(
            km.map_key(&k("(")),
            vec![Command::InsertDelimiters {
                open: '(',
                close: ')'
            }]
        );
    }

    #[test]
    fn autocorrect_two_char() {
        let mut km = Keymap::new();
        assert_eq!(km.map_key(&k("<")), vec![sym("<", MathClass::Rel)]);
        assert_eq!(
            km.map_key(&k("=")),
            vec![Command::DeleteBackward, sym("\\leq", MathClass::Rel)]
        );
    }

    #[test]
    fn implies_arrow() {
        let mut km = Keymap::new();
        km.map_key(&k("="));
        assert_eq!(
            km.map_key(&k(">")),
            vec![Command::DeleteBackward, sym("\\implies", MathClass::Rel)]
        );
    }

    #[test]
    fn word_on_space_converts() {
        let mut km = Keymap::new();
        km.map_key(&k("p"));
        km.map_key(&k("i"));
        assert_eq!(
            km.map_key(&k(" ")),
            vec![
                Command::DeleteBackward,
                Command::DeleteBackward,
                sym("\\pi", MathClass::Ord)
            ]
        );
    }

    /// `map_text` must replay every character through `map_char` so shortcuts still fire.
    #[test]
    fn map_text_replays_word_lookup_fraction_and_autocorrect() {
        // `map_text` queues inserts before the space replacement, matching typed input order.
        let mut km = Keymap::new();
        assert_eq!(
            km.map_text("pi "),
            vec![
                sym("p", MathClass::Ord),
                sym("i", MathClass::Ord),
                Command::DeleteBackward,
                Command::DeleteBackward,
                sym("\\pi", MathClass::Ord)
            ]
        );

        let mut km = Keymap::new();
        assert_eq!(
            km.map_text("a/b"),
            vec![
                sym("a", MathClass::Ord),
                Command::InsertFraction(FracStyle::Bar),
                sym("b", MathClass::Ord),
            ]
        );

        let mut km = Keymap::new();
        assert_eq!(
            km.map_text("a<=b"),
            vec![
                sym("a", MathClass::Ord),
                sym("<", MathClass::Rel),
                Command::DeleteBackward,
                sym("\\leq", MathClass::Rel),
                sym("b", MathClass::Ord),
            ]
        );
    }

    #[test]
    fn operator_word_converts() {
        let mut km = Keymap::new();
        for c in ["s", "i", "n"] {
            km.map_key(&k(c));
        }
        assert_eq!(
            km.map_key(&k(" ")),
            vec![
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                sym("\\sin", MathClass::Op)
            ]
        );
    }

    #[test]
    fn bare_space_inserts_nothing() {
        let mut km = Keymap::new();
        assert_eq!(km.map_key(&k(" ")), Vec::<Command>::new());
    }

    #[test]
    fn unknown_word_then_space_is_dropped() {
        let mut km = Keymap::new();
        km.map_key(&k("x"));
        km.map_key(&k("y"));
        assert_eq!(km.map_key(&k(" ")), Vec::<Command>::new());
    }

    #[test]
    fn plain_letter_inserts_atom() {
        let mut km = Keymap::new();
        assert_eq!(km.map_key(&k("a")), vec![sym("a", MathClass::Ord)]);
    }

    #[test]
    fn structure_word_builds_bigop() {
        let mut km = Keymap::new();
        for c in ["s", "u", "m"] {
            km.map_key(&k(c));
        }
        assert_eq!(
            km.map_key(&k(" ")),
            vec![
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::InsertBigOp(Symbol {
                    latex: "\\sum".into(),
                    class: MathClass::Op
                }),
            ]
        );
    }

    #[test]
    fn structure_word_builds_fraction() {
        let mut km = Keymap::new();
        for c in ["f", "r", "a", "c"] {
            km.map_key(&k(c));
        }
        assert_eq!(
            km.map_key(&k(" ")),
            vec![
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::InsertFraction(FracStyle::Bar),
            ]
        );
    }

    #[test]
    fn structure_word_builds_pmatrix() {
        let mut km = Keymap::new();
        for c in ["p", "m", "a", "t", "r", "i", "x"] {
            km.map_key(&k(c));
        }
        assert_eq!(
            km.map_key(&k(" ")),
            vec![
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::InsertMatrix {
                    env: MatrixEnv::Pmatrix,
                    rows: 2,
                    cols: 2
                },
            ]
        );
    }

    #[test]
    fn structure_word_builds_cases() {
        let mut km = Keymap::new();
        for c in ["c", "a", "s", "e", "s"] {
            km.map_key(&k(c));
        }
        assert_eq!(
            km.map_key(&k(" ")),
            vec![
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::DeleteBackward,
                Command::InsertMatrix {
                    env: MatrixEnv::Cases,
                    rows: 2,
                    cols: 2
                },
            ]
        );
    }

    #[test]
    fn host_defined_word_overrides_and_inserts() {
        let mut km = Keymap::new();
        km.define_word("RR", vec![sym("\\mathbb{R}", MathClass::Ord)]);
        for c in ["R", "R"] {
            km.map_key(&k(c));
        }
        assert_eq!(
            km.map_key(&k(" ")),
            vec![
                Command::DeleteBackward,
                Command::DeleteBackward,
                sym("\\mathbb{R}", MathClass::Ord)
            ]
        );
    }

    #[test]
    fn override_shadows_builtin() {
        let mut km = Keymap::new();
        km.define_word("pi", vec![sym("\\varpi", MathClass::Ord)]);
        for c in ["p", "i"] {
            km.map_key(&k(c));
        }
        assert_eq!(
            km.map_key(&k(" ")).last().cloned(),
            Some(sym("\\varpi", MathClass::Ord))
        );
    }

    #[test]
    fn entries_are_enumerable_for_popover() {
        let km = Keymap::new();
        let words: Vec<&str> = km.entries().iter().map(|e| e.word).collect();
        assert!(words.contains(&"frac")); // structure
        assert!(words.contains(&"sum")); // big operator
        assert!(words.contains(&"alpha")); // symbol
        assert!(words.contains(&"sin")); // operator
    }
}