kanata_parser/cfg/
zippychord.rs

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
//! Zipchord-like parsing. Probably not 100% compatible.
//!
//! Example lines in input file.
//! The " => " string represents a tab character.
//!
//! "dy => day"
//!   -> chord: (d y)
//!   -> output: "day"
//!
//! "dy => day"
//! "dy 1 => Monday"
//!   -> chord: (d y)
//!   -> output: "day"
//!   -> chord: (d y)
//!   -> output: "Monday"; "day" gets erased
//!
//! " abc => Alphabet"
//!   -> chord: (space a b c)
//!   -> output: "Alphabet"
//!
//! "r df => recipient"
//!   -> chord: (r)
//!   -> output: nothing yet, just type r
//!   -> chord: (d f)
//!   -> output: "recipient"
//!
//! " w  a => Washington"
//!   -> chord: (space w)
//!   -> output: nothing yet, type spacebar+w in whatever true order they were pressed
//!   -> chord: (space a)
//!   -> output: "Washington"
//!   -> note: do observe the two spaces between 'w' and 'a'
use super::*;
use crate::bail_expr;

#[cfg(not(feature = "zippychord"))]
#[derive(Debug, Clone, Default)]
pub struct ZchPossibleChords();
#[cfg(not(feature = "zippychord"))]
#[derive(Debug, Clone, Default)]
pub struct ZchConfig();
#[cfg(not(feature = "zippychord"))]
fn parse_zippy_inner(
    exprs: &[SExpr],
    _s: &ParserState,
    _f: &mut FileContentProvider,
) -> Result<(ZchPossibleChords, ZchConfig)> {
    bail_expr!(&exprs[0], "Kanata was not compiled with the \"zippychord\" feature. This configuration is unsupported")
}

pub(crate) fn parse_zippy(
    exprs: &[SExpr],
    s: &ParserState,
    f: &mut FileContentProvider,
) -> Result<(ZchPossibleChords, ZchConfig)> {
    parse_zippy_inner(exprs, s, f)
}

#[cfg(feature = "zippychord")]
pub use inner::*;
#[cfg(feature = "zippychord")]
mod inner {
    use super::*;

    use crate::anyhow_expr;
    use crate::subset::*;

    use parking_lot::Mutex;

    /// All possible chords.
    #[derive(Debug, Clone, Default)]
    pub struct ZchPossibleChords(pub SubsetMap<u16, Arc<ZchChordOutput>>);
    impl ZchPossibleChords {
        pub fn is_empty(&self) -> bool {
            self.0.is_empty()
        }
    }

    /// Tracks current input to check against possible chords.
    /// This does not store by the input order;
    /// instead it is by some consistent ordering for
    /// hashing into the possible chord map.
    #[derive(Debug, Clone, Default, PartialEq, Eq)]
    pub struct ZchInputKeys {
        zch_inputs: ZchSortedChord,
    }
    impl ZchInputKeys {
        pub fn zchik_new() -> Self {
            Self {
                zch_inputs: ZchSortedChord {
                    zch_keys: Vec::new(),
                },
            }
        }
        pub fn zchik_contains(&self, osc: OsCode) -> bool {
            self.zch_inputs.zch_keys.contains(&osc.into())
        }
        pub fn zchik_insert(&mut self, osc: OsCode) {
            self.zch_inputs.zch_insert(osc.into());
        }
        pub fn zchik_remove(&mut self, osc: OsCode) {
            self.zch_inputs.zch_keys.retain(|k| *k != osc.into());
        }
        pub fn zchik_len(&self) -> usize {
            self.zch_inputs.zch_keys.len()
        }
        pub fn zchik_clear(&mut self) {
            self.zch_inputs.zch_keys.clear()
        }
        pub fn zchik_keys(&self) -> &[u16] {
            &self.zch_inputs.zch_keys
        }
        pub fn zchik_is_empty(&self) -> bool {
            self.zch_inputs.zch_keys.is_empty()
        }
    }

    #[derive(Debug, Default, Clone, Hash, PartialEq, Eq)]
    /// Sorted consistently by some arbitrary key order;
    /// as opposed to, for example, simply the user press order.
    pub struct ZchSortedChord {
        zch_keys: Vec<u16>,
    }
    impl ZchSortedChord {
        pub fn zch_insert(&mut self, key: u16) {
            match self.zch_keys.binary_search(&key) {
                // Q: what is the meaning of Ok vs. Err?
                // A: Ok means the element already in vector @ `pos`. Normally this wouldn't be
                // expected to happen but it turns out that key repeat might get in the way of this
                // assumption. Err means element does not exist and returns the correct insert position.
                Ok(_pos) => {}
                Err(pos) => self.zch_keys.insert(pos, key),
            }
        }
    }

    /// A chord.
    ///
    /// If any followups exist it will be Some.
    /// E.g. with:
    /// - dy   -> day
    /// - dy 1 -> Monday
    /// - dy 2 -> Tuesday
    ///
    /// the output will be "day" and the Monday+Tuesday chords will be in `followups`.
    #[derive(Debug, Clone)]
    pub struct ZchChordOutput {
        pub zch_output: Box<[ZchOutput]>,
        pub zch_followups: Option<Arc<Mutex<ZchPossibleChords>>>,
    }

    /// Zch output can be uppercase, lowercase, altgr, and shift-altgr characters.
    /// The parser should ensure all `OsCode`s in variants containing them
    /// are visible characters that are backspacable.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum ZchOutput {
        Lowercase(OsCode),
        Uppercase(OsCode),
        AltGr(OsCode),
        ShiftAltGr(OsCode),
        NoEraseLowercase(OsCode),
        NoEraseUppercase(OsCode),
        NoEraseAltGr(OsCode),
        NoEraseShiftAltGr(OsCode),
    }

    impl ZchOutput {
        pub fn osc(self) -> OsCode {
            use ZchOutput::*;
            match self {
                Lowercase(osc)
                | Uppercase(osc)
                | AltGr(osc)
                | ShiftAltGr(osc)
                | NoEraseLowercase(osc)
                | NoEraseUppercase(osc)
                | NoEraseAltGr(osc)
                | NoEraseShiftAltGr(osc) => osc,
            }
        }
        pub fn osc_and_is_noerase(self) -> (OsCode, bool) {
            use ZchOutput::*;
            match self {
                Lowercase(osc) | Uppercase(osc) | AltGr(osc) | ShiftAltGr(osc) => (osc, false),
                NoEraseLowercase(osc)
                | NoEraseUppercase(osc)
                | NoEraseAltGr(osc)
                | NoEraseShiftAltGr(osc) => (osc, true),
            }
        }
        pub fn display_len(outs: impl AsRef<[Self]>) -> i16 {
            outs.as_ref().iter().copied().fold(0i16, |mut len, out| {
                len += out.output_char_count();
                len
            })
        }
        pub fn output_char_count(self) -> i16 {
            match self.osc_and_is_noerase() {
                (OsCode::KEY_BACKSPACE, _) => -1,
                (_, false) => 1,
                (_, true) => 0,
            }
        }
    }

    /// User configuration for smart space.
    ///
    /// - `Full`         = add spaces after words, remove these spaces after typing punctuation.
    /// - `AddSpaceOnly` = add spaces after words
    /// - `Disabled`     = do nothing
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum ZchSmartSpaceCfg {
        Full,
        AddSpaceOnly,
        Disabled,
    }

    #[derive(Debug)]
    pub struct ZchConfig {
        /// When, during typing, chord fails to activate, zippychord functionality becomes temporarily
        /// disabled. This is to avoid accidental chord activations when typing normally, as opposed to
        /// intentionally trying to activate a chord. The duration of temporary disabling is determined
        /// by this configuration item. Re-enabling also happens when word-splitting characters are
        /// typed, for example typing  a space or a comma, but a pause of all typing activity lasting a
        /// number of milliseconds equal to this configuration will also re-enable chording even if
        /// typing within a single word.
        pub zch_cfg_ticks_wait_enable: u16,

        /// Assuming zippychording is enabled, when the first press happens this deadline will begin
        /// and if no chords are completed within the deadline, zippychording will be disabled
        /// temporarily (see `zch_cfg_ticks_wait_enable`). You may want a long or short deadline
        /// depending on your use case. If you are primarily typing normally, with chords being used
        /// occasionally being used, you may want a short deadline so that regular typing will be
        /// unlikely to activate any chord. However, if you primarily type with chords, you may want a
        /// longer deadline to give you more time to complete the intended chord (e.g. in case of
        /// overlaps). With a long deadline you should be very intentional about pressing and releasing
        /// an individual key to begin a sequence of regular typing to trigger the disabling of
        /// zippychord. If, after the first press, a chord activates, this deadline will reset to
        /// enable further chord activations.
        pub zch_cfg_ticks_chord_deadline: u16,

        /// User configuration for smart space. See `pub enum ZchSmartSpaceCfg`.
        pub zch_cfg_smart_space: ZchSmartSpaceCfg,

        /// Define keys for punctuation, which is relevant to smart space auto-erasure of added spaces.
        pub zch_cfg_smart_space_punctuation: HashSet<ZchOutput>,
    }

    impl Default for ZchConfig {
        fn default() -> Self {
            Self {
                zch_cfg_ticks_wait_enable: 500,
                zch_cfg_ticks_chord_deadline: 500,
                zch_cfg_smart_space: ZchSmartSpaceCfg::Disabled,
                zch_cfg_smart_space_punctuation: {
                    let mut puncs = HashSet::default();
                    puncs.insert(ZchOutput::Lowercase(OsCode::KEY_DOT));
                    puncs.insert(ZchOutput::Lowercase(OsCode::KEY_COMMA));
                    puncs.insert(ZchOutput::Lowercase(OsCode::KEY_SEMICOLON));
                    puncs.shrink_to_fit();
                    puncs
                },
            }
        }
    }

    const NO_ERASE: &str = "no-erase";
    const SINGLE_OUTPUT_MULTI_KEY: &str = "single-output";

    enum ZchIoMappingType {
        NoErase,
        SingleOutput,
    }
    impl ZchIoMappingType {
        fn try_parse(expr: &SExpr, vars: Option<&HashMap<String, SExpr>>) -> Result<Self> {
            use ZchIoMappingType::*;
            expr.atom(vars)
                .and_then(|name| match name {
                    NO_ERASE => Some(NoErase),
                    SINGLE_OUTPUT_MULTI_KEY => Some(SingleOutput),
                    _ => None,
                })
                .ok_or_else(|| {
                    anyhow_expr!(
                        &expr,
                        "Unknown output type. Must be one of:\nno-erase | single-output"
                    )
                })
        }
    }

    #[cfg(feature = "zippychord")]
    pub(super) fn parse_zippy_inner(
        exprs: &[SExpr],
        s: &ParserState,
        f: &mut FileContentProvider,
    ) -> Result<(ZchPossibleChords, ZchConfig)> {
        use crate::subset::GetOrIsSubsetOfKnownKey::*;

        if exprs.len() < 2 {
            bail_expr!(
                &exprs[0],
                "There must be a filename following the zippy definition.\nFound {}",
                exprs.len() - 1
            );
        }

        let Some(file_name) = exprs[1].atom(s.vars()) else {
            bail_expr!(&exprs[1], "Filename must be a string, not a list.");
        };

        let mut config = ZchConfig::default();

        const KEY_NAME_MAPPINGS: &str = "output-character-mappings";
        const IDLE_REACTIVATE_TIME: &str = "idle-reactivate-time";
        const CHORD_DEADLINE: &str = "on-first-press-chord-deadline";
        const SMART_SPACE: &str = "smart-space";
        const SMART_SPACE_PUNCTUATION: &str = "smart-space-punctuation";

        let mut idle_reactivate_time_seen = false;
        let mut key_name_mappings_seen = false;
        let mut chord_deadline_seen = false;
        let mut smart_space_seen = false;
        let mut smart_space_punctuation_seen = false;
        let mut smart_space_punctuation_val_expr = None;

        let mut user_cfg_char_to_output: HashMap<char, Vec<ZchOutput>> = HashMap::default();
        let mut pairs = exprs[2..].chunks_exact(2);
        for pair in pairs.by_ref() {
            let config_name = &pair[0];
            let config_value = &pair[1];

            match config_name.atom(s.vars()).ok_or_else(|| {
                anyhow_expr!(
                    config_name,
                    "A configuration name must be a string, not a list"
                )
            })? {
                IDLE_REACTIVATE_TIME => {
                    if idle_reactivate_time_seen {
                        bail_expr!(
                            config_name,
                            "This is the 2nd instance; it can only be defined once"
                        );
                    }
                    idle_reactivate_time_seen = true;
                    config.zch_cfg_ticks_wait_enable =
                        parse_u16(config_value, s, IDLE_REACTIVATE_TIME)?;
                }

                CHORD_DEADLINE => {
                    if chord_deadline_seen {
                        bail_expr!(
                            config_name,
                            "This is the 2nd instance; it can only be defined once"
                        );
                    }
                    chord_deadline_seen = true;
                    config.zch_cfg_ticks_chord_deadline =
                        parse_u16(config_value, s, CHORD_DEADLINE)?;
                }

                SMART_SPACE => {
                    if smart_space_seen {
                        bail_expr!(
                            config_name,
                            "This is the 2nd instance; it can only be defined once"
                        );
                    }
                    smart_space_seen = true;
                    config.zch_cfg_smart_space = config_value
                        .atom(s.vars())
                        .and_then(|val| match val {
                            "none" => Some(ZchSmartSpaceCfg::Disabled),
                            "full" => Some(ZchSmartSpaceCfg::Full),
                            "add-space-only" => Some(ZchSmartSpaceCfg::AddSpaceOnly),
                            _ => None,
                        })
                        .ok_or_else(|| {
                            anyhow_expr!(&config_value, "Must be: none | full | add-space-only")
                        })?;
                }

                SMART_SPACE_PUNCTUATION => {
                    if smart_space_punctuation_seen {
                        bail_expr!(
                            config_name,
                            "This is the 2nd instance; it can only be defined once"
                        );
                    }
                    smart_space_punctuation_seen = true;
                    // Need to save and parse this later since it makes use of KEY_NAME_MAPPINGS.
                    smart_space_punctuation_val_expr = Some(config_value);
                }

                KEY_NAME_MAPPINGS => {
                    if key_name_mappings_seen {
                        bail_expr!(
                            config_name,
                            "This is the 2nd instance; it can only be defined once"
                        );
                    }
                    key_name_mappings_seen = true;
                    let mut mappings = config_value
                        .list(s.vars())
                        .ok_or_else(|| {
                            anyhow_expr!(
                                config_value,
                                "{KEY_NAME_MAPPINGS} must be followed by a list"
                            )
                        })?
                        .chunks_exact(2);

                    for mapping_pair in mappings.by_ref() {
                        let input = mapping_pair[0]
                            .atom(None)
                            .ok_or_else(|| {
                                anyhow_expr!(
                                    &mapping_pair[0],
                                    "key mapping input does not use lists"
                                )
                            })?
                            .trim_atom_quotes();
                        if input.chars().count() != 1 {
                            bail_expr!(&mapping_pair[0], "Inputs should be exactly one character");
                        }
                        let input_char = input.chars().next().expect("count is 1");

                        let output = match mapping_pair[1].atom(s.vars()) {
                            Some(o) => vec![parse_single_zippy_output_mapping(
                                o,
                                &mapping_pair[1],
                                false,
                            )?],
                            None => {
                                // note for unwrap below: must be list if not atom
                                let output_list = mapping_pair[1].list(s.vars()).unwrap();
                                if output_list.is_empty() {
                                    bail_expr!(
                                        &mapping_pair[1],
                                        "Empty list is invalid for zippy output mapping."
                                    );
                                }
                                let output_type =
                                    ZchIoMappingType::try_parse(&output_list[0], s.vars())?;
                                match output_type {
                                    ZchIoMappingType::NoErase => {
                                        const ERR: &str = "expects a single key or output chord.";
                                        if output_list.len() != 2 {
                                            anyhow_expr!(&output_list[1], "{NO_ERASE} {ERR}");
                                        }
                                        let output =
                                            output_list[1].atom(s.vars()).ok_or_else(|| {
                                                anyhow_expr!(&output_list[1], "{NO_ERASE} {ERR}")
                                            })?;
                                        vec![parse_single_zippy_output_mapping(
                                            output,
                                            &output_list[1],
                                            true,
                                        )?]
                                    }
                                    ZchIoMappingType::SingleOutput => {
                                        if output_list.len() < 2 {
                                            anyhow_expr!(&output_list[1], "{SINGLE_OUTPUT_MULTI_KEY} expects one or more keys or output chords.");
                                        }
                                        let all_params_except_last =
                                            &output_list[1..output_list.len() - 1];
                                        let mut outs = vec![];
                                        for expr in all_params_except_last {
                                            let output = expr
                                            .atom(s.vars())
                                            .ok_or_else(|| {
                                                anyhow_expr!(&output_list[1], "{SINGLE_OUTPUT_MULTI_KEY} does not allow list parameters.")
                                            })?;
                                            let out = parse_single_zippy_output_mapping(
                                                output,
                                                &output_list[1],
                                                true,
                                            )?;
                                            outs.push(out);
                                        }
                                        let last_expr = &output_list.last().unwrap(); // non-empty, checked length already
                                        let last_out = last_expr
                                        .atom(s.vars())
                                        .ok_or_else(|| {
                                            anyhow_expr!(last_expr, "{SINGLE_OUTPUT_MULTI_KEY} does not allow list parameters.")
                                        })?;
                                        outs.push(parse_single_zippy_output_mapping(
                                            last_out, last_expr, false,
                                        )?);
                                        outs
                                    }
                                }
                            }
                        };

                        if user_cfg_char_to_output.insert(input_char, output).is_some() {
                            bail_expr!(&mapping_pair[0], "Duplicate character, not allowed");
                        }
                    }

                    let rem = mappings.remainder();
                    if !rem.is_empty() {
                        bail_expr!(&rem[0], "zippy input is missing its output mapping");
                    }
                }
                _ => bail_expr!(config_name, "Unknown zippy configuration name"),
            }
        }

        let rem = pairs.remainder();
        if !rem.is_empty() {
            bail_expr!(&rem[0], "zippy config name is missing its value");
        }

        if let Some(val) = smart_space_punctuation_val_expr {
            config.zch_cfg_smart_space_punctuation = val
                .list(s.vars())
                .ok_or_else(|| {
                    anyhow_expr!(val, "{SMART_SPACE_PUNCTUATION} must be followed by a list")
                })?
                .iter()
                .try_fold(vec![], |mut puncs, punc_expr| -> Result<Vec<ZchOutput>> {
                    let punc = punc_expr
                        .atom(s.vars())
                        .ok_or_else(|| anyhow_expr!(&punc_expr, "Lists are not allowed"))?;

                    if punc.chars().count() == 1 {
                        let c = punc.chars().next().unwrap(); // checked count above
                        if let Some(out) = user_cfg_char_to_output.get(&c) {
                            if out.len() > 1 {
                                bail_expr!(
                                    punc_expr,
                                    "This character is a single-output with multiple keys\n
                                       and is not yet supported as use for punctuation."
                                );
                            }
                            puncs.push(out[0]);
                            return Ok(puncs);
                        }
                    }

                    let osc = str_to_oscode(punc)
                        .ok_or_else(|| anyhow_expr!(&punc_expr, "Unknown key name"))?;
                    puncs.push(ZchOutput::Lowercase(osc));

                    Ok(puncs)
                })?
                .into_iter()
                .collect();
            config.zch_cfg_smart_space_punctuation.shrink_to_fit();
        }

        // process zippy file
        let input_data = f
            .get_file_content(file_name.as_ref())
            .map_err(|e| anyhow_expr!(&exprs[1], "Failed to read file:\n{e}"))?;
        let res = input_data
            .lines()
            .enumerate()
            .filter(|(_, line)| !line.trim().is_empty() && !line.trim().starts_with("//"))
            .try_fold(
                Arc::new(Mutex::new(ZchPossibleChords(SubsetMap::ssm_new()))),
                |zch, (line_number, line)| {
                    let Some((input, output)) = line.split_once('\t') else {
                        bail_expr!(
                        &exprs[1],
                        "Input and output are separated by a tab, but found no tab:\n{}: {line}",
                        line_number + 1
                    );
                    };
                    if input.is_empty() {
                        bail_expr!(
                            &exprs[1],
                            "No input defined; line must not begin with a tab:\n{}: {line}",
                            line_number + 1
                        );
                    }

                    let mut char_buf: [u8; 4] = [0; 4];
                    let output = {
                        output
                            .chars()
                            .try_fold(vec![], |mut zch_output, out_char| -> Result<_> {
                                if let Some(out) = user_cfg_char_to_output.get(&out_char) {
                                    zch_output.extend(out.iter());
                                    return Ok(zch_output);
                                }

                                let out_key = out_char.to_lowercase().next().unwrap();
                                let key_name = out_key.encode_utf8(&mut char_buf);
                                let osc = match key_name as &str {
                                    " " => OsCode::KEY_SPACE,
                                    _ => str_to_oscode(key_name).ok_or_else(|| {
                                        anyhow_expr!(
                                            &exprs[1],
                                            "Unknown output key name '{}':\n{}: {line}",
                                            out_char,
                                            line_number + 1,
                                        )
                                    })?,
                                };
                                let out = match out_char.is_uppercase() {
                                    true => ZchOutput::Uppercase(osc),
                                    false => ZchOutput::Lowercase(osc),
                                };
                                zch_output.push(out);
                                Ok(zch_output)
                            })?
                            .into_boxed_slice()
                    };
                    let mut input_left_to_parse = input;
                    let mut chord_chars;
                    let mut input_chord = ZchInputKeys::zchik_new();
                    let mut is_space_included;
                    let mut possible_chords_map = zch.clone();
                    let mut next_map: Option<Arc<Mutex<_>>>;

                    while !input_left_to_parse.is_empty() {
                        input_chord.zchik_clear();

                        // Check for a starting space.
                        (is_space_included, input_left_to_parse) =
                            match input_left_to_parse.strip_prefix(' ') {
                                None => (false, input_left_to_parse),
                                Some(i) => (true, i),
                            };
                        if is_space_included {
                            input_chord.zchik_insert(OsCode::KEY_SPACE);
                        }

                        // Parse chord until next space.
                        (chord_chars, input_left_to_parse) =
                            match input_left_to_parse.split_once(' ') {
                                Some(split) => split,
                                None => (input_left_to_parse, ""),
                            };

                        chord_chars
                            .chars()
                            .try_fold((), |_, chord_char| -> Result<()> {
                                let key_name = chord_char.encode_utf8(&mut char_buf);
                                let osc = str_to_oscode(key_name).ok_or_else(|| {
                                    anyhow_expr!(
                                        &exprs[1],
                                        "Unknown input key name: '{key_name}':\n{}: {line}",
                                        line_number + 1
                                    )
                                })?;
                                input_chord.zchik_insert(osc);
                                Ok(())
                            })?;

                        let output_for_input_chord = possible_chords_map
                            .lock()
                            .0
                            .ssm_get_or_is_subset_ksorted(input_chord.zchik_keys());
                        match (input_left_to_parse.is_empty(), output_for_input_chord) {
                            (true, HasValue(_)) => {
                                bail_expr!(
                            &exprs[1],
                            "Found duplicate input chord, which is disallowed {input}:\n{}: {line}",
                            line_number + 1
                        );
                            }
                            (true, _) => {
                                possible_chords_map.lock().0.ssm_insert_ksorted(
                                    input_chord.zchik_keys(),
                                    Arc::new(ZchChordOutput {
                                        zch_output: output,
                                        zch_followups: None,
                                    }),
                                );
                                break;
                            }
                            (false, HasValue(next_nested_map)) => {
                                match &next_nested_map.zch_followups {
                                    None => {
                                        let map = Arc::new(Mutex::new(ZchPossibleChords(
                                            SubsetMap::ssm_new(),
                                        )));
                                        next_map = Some(map.clone());
                                        possible_chords_map.lock().0.ssm_insert_ksorted(
                                            input_chord.zchik_keys(),
                                            ZchChordOutput {
                                                zch_output: next_nested_map.zch_output.clone(),
                                                zch_followups: Some(map),
                                            }
                                            .into(),
                                        );
                                    }
                                    Some(followup) => {
                                        next_map = Some(followup.clone());
                                    }
                                }
                            }
                            (false, _) => {
                                let map =
                                    Arc::new(Mutex::new(ZchPossibleChords(SubsetMap::ssm_new())));
                                next_map = Some(map.clone());
                                possible_chords_map.lock().0.ssm_insert_ksorted(
                                    input_chord.zchik_keys(),
                                    Arc::new(ZchChordOutput {
                                        zch_output: Box::new([]),
                                        zch_followups: Some(map),
                                    }),
                                );
                            }
                        };
                        if let Some(map) = next_map.take() {
                            possible_chords_map = map;
                        }
                    }
                    Ok(zch)
                },
            )?;
        Ok((
            Arc::into_inner(res).expect("no other refs").into_inner(),
            config,
        ))
    }

    fn parse_single_zippy_output_mapping(
        output: &str,
        output_expr: &SExpr,
        is_noerase: bool,
    ) -> Result<ZchOutput> {
        let (output_mods, output_key) = parse_mod_prefix(output)?;
        if output_mods.contains(&KeyCode::LShift) && output_mods.contains(&KeyCode::RShift) {
            bail_expr!(
                output_expr,
                "Both shifts are used which is redundant, use only one."
            );
        }
        if output_mods
            .iter()
            .any(|m| !matches!(m, KeyCode::LShift | KeyCode::RShift | KeyCode::RAlt))
        {
            bail_expr!(output_expr, "Only S- and AG- are supported.");
        }
        let output_osc = str_to_oscode(output_key)
            .ok_or_else(|| anyhow_expr!(output_expr, "unknown key name"))?;
        let output = match output_mods.len() {
            0 => match is_noerase {
                false => ZchOutput::Lowercase(output_osc),
                true => ZchOutput::NoEraseLowercase(output_osc),
            },
            1 => match output_mods[0] {
                KeyCode::LShift | KeyCode::RShift => match is_noerase {
                    false => ZchOutput::Uppercase(output_osc),
                    true => ZchOutput::NoEraseUppercase(output_osc),
                },
                KeyCode::RAlt => match is_noerase {
                    false => ZchOutput::AltGr(output_osc),
                    true => ZchOutput::NoEraseAltGr(output_osc),
                },
                _ => unreachable!("forbidden by earlier parsing"),
            },
            2 => match is_noerase {
                false => ZchOutput::ShiftAltGr(output_osc),
                true => ZchOutput::NoEraseShiftAltGr(output_osc),
            },
            _ => {
                unreachable!("contains at most: altgr and one of the shifts")
            }
        };
        Ok(output)
    }
}