par-term-config 0.16.0

Configuration system for par-term terminal emulator
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! Keybinding management methods for `Config`.
//!
//! Covers:
//! - Merging default keybindings and status-bar widgets into user config
//! - Generating / synchronising snippet and action keybindings

use super::config_struct::Config;
use crate::types::KeyBinding;
use std::collections::{BTreeSet, HashSet};

/// Action ids renamed between releases, as `(previous id, current id)`.
///
/// Applied in place at load: the user's chord moves to the current id instead
/// of a default for the new id being added alongside it (UX.md §3.3 migration
/// rule 2). Dispatch also resolves the previous ids through
/// [`current_action_id`], so a binding that bypasses the load-time migration
/// (a hand-edited reload, a snippet-generated row) still runs.
///
/// UX.md T7: split actions name where the new pane goes. `split_horizontal`
/// stacked the panes (new pane below) and `split_vertical` placed them side
/// by side (new pane to the right).
pub const ACTION_RENAMES: &[(&str, &str)] = &[
    ("split_horizontal", "split_down"),
    ("split_vertical", "split_right"),
    // UX.md A23: the public, documented detach id.
    ("mux-detach", "detach"),
    // UX.md A16: one picker lists par-mux and tmux sessions.
    ("toggle_tmux_session_picker", "toggle_session_picker"),
];

/// Linux/Windows default chords that moved, as `(action, previous chord, new
/// chord)`. UX.md D3: Ctrl+Shift+B became the leader key, so the background
/// shader toggle moved to Ctrl+Alt+B; a saved config still holding the old
/// row would otherwise shadow the leader forever.
const MOVED_DEFAULT_CHORDS: &[(&str, &str, &str)] =
    &[("toggle_background_shader", "Ctrl+Shift+B", "Ctrl+Alt+B")];

/// The current id for `action`, following [`ACTION_RENAMES`]; any other id is
/// returned unchanged.
pub fn current_action_id(action: &str) -> &str {
    ACTION_RENAMES
        .iter()
        .find(|(previous, _)| *previous == action)
        .map_or(action, |(_, current)| current)
}

/// Canonical comparison form of a chord string, for duplicate-chord detection
/// at config-load time (UX.md §3.3 rule 1).
///
/// Mirrors the modifier vocabulary of `par_term_keybindings::parser`, folding
/// synonyms (`Ctrl`/`Control`, `Alt`/`Option`, `Super`/`Cmd`/`Command`/`Meta`/
/// `Win`) into one token and resolving `CmdOrCtrl` to the platform modifier it
/// stands for, so `CmdOrCtrl+Shift+P` and `Shift+CmdOrCtrl+P` compare equal on
/// every platform. The parsed registry remains the match-time authority; this
/// catches the spellings users and defaults actually write.
///
/// Returns `None` for chords this cannot canonicalize (no key, more than one
/// key). A `None` chord never claims anything — the registry still rejects it
/// at registration if it is invalid.
pub(crate) fn canonical_chord(key: &str) -> Option<String> {
    let parts: Vec<&str> = key.split('+').map(str::trim).collect();
    if parts.is_empty() {
        return None;
    }

    let mut modifiers: BTreeSet<&str> = BTreeSet::new();
    let mut key_part: Option<&str> = None;

    for (i, part) in parts.iter().enumerate() {
        let is_last = i == parts.len() - 1;
        let part_lower = part.to_lowercase();

        let is_modifier = match part_lower.as_str() {
            "ctrl" | "control" => modifiers.insert("ctrl"),
            "alt" | "option" => modifiers.insert("alt"),
            "shift" => modifiers.insert("shift"),
            "super" | "cmd" | "command" | "meta" | "win" => modifiers.insert("super"),
            "cmdorctrl" => {
                if cfg!(target_os = "macos") {
                    modifiers.insert("super")
                } else {
                    modifiers.insert("ctrl")
                }
            }
            _ => false,
        };

        if !is_modifier {
            if key_part.is_some() {
                // Same shape the parser rejects: two non-modifier tokens.
                return None;
            }
            key_part = Some(part);
        } else if is_last {
            // Ends with a modifier and no key.
            return None;
        }
    }

    let key = key_part?;
    if key.is_empty() {
        return None;
    }

    let mut canonical = String::new();
    for modifier in &modifiers {
        canonical.push_str(modifier);
        canonical.push('+');
    }
    canonical.push_str(&key.to_lowercase());
    Some(canonical)
}

impl Config {
    /// Merge default keybindings into the user's config, applying the UX.md
    /// §3.3 migration rule: renamed actions migrate in place first, then a
    /// new or moved default is added only if its action id is unbound AND its
    /// chord is unclaimed by any other binding.
    pub(crate) fn merge_default_keybindings(&mut self) {
        self.migrate_renamed_keybinding_actions();
        if !cfg!(target_os = "macos") {
            self.migrate_moved_default_chords_from(MOVED_DEFAULT_CHORDS);
        }
        self.merge_default_keybindings_from(&crate::defaults::keybindings());
    }

    /// Move a binding still on a previous default chord to its new default
    /// (migration rule 2 for chords): only the exact `(action, old chord)`
    /// row moves, and only while the new chord is unclaimed — a user who
    /// rebound either side keeps their choice.
    fn migrate_moved_default_chords_from(&mut self, moves: &[(&str, &str, &str)]) {
        for (action, old, new) in moves {
            let (Some(old), Some(new_canonical)) = (canonical_chord(old), canonical_chord(new))
            else {
                continue;
            };
            if self
                .keybindings
                .iter()
                .any(|kb| canonical_chord(&kb.key).as_deref() == Some(new_canonical.as_str()))
            {
                continue;
            }
            if let Some(binding) = self.keybindings.iter_mut().find(|kb| {
                kb.action == *action && canonical_chord(&kb.key).as_deref() == Some(old.as_str())
            }) {
                log::info!(
                    "Moving '{}' from its previous default chord '{}' to '{}'",
                    action,
                    binding.key,
                    new
                );
                binding.key = new.to_string();
            }
        }
    }

    /// Rewrite keybinding action ids through [`ACTION_RENAMES`], keeping each
    /// binding's chord (migration rule 2).
    pub(crate) fn migrate_renamed_keybinding_actions(&mut self) {
        self.migrate_renamed_keybinding_actions_from(ACTION_RENAMES);
    }

    fn migrate_renamed_keybinding_actions_from(&mut self, renames: &[(&str, &str)]) {
        for binding in &mut self.keybindings {
            if let Some((_, current)) = renames
                .iter()
                .find(|(previous, _)| *previous == binding.action)
            {
                log::info!(
                    "Migrating keybinding action '{}' -> '{}' (chord '{}' kept)",
                    binding.action,
                    current,
                    binding.key
                );
                binding.action = current.to_string();
            }
        }
    }

    /// Add defaults whose action id is unbound and whose chord is unclaimed
    /// (migration rule 1). Split from [`Self::merge_default_keybindings`] so
    /// tests can drive the claim check with synthetic future defaults.
    fn merge_default_keybindings_from(&mut self, default_keybindings: &[KeyBinding]) {
        // Owned strings: the sets outlive the pushes into `self.keybindings`.
        let existing_actions: HashSet<String> = self
            .keybindings
            .iter()
            .map(|kb| kb.action.clone())
            .collect();
        let mut claimed_chords: HashSet<String> = self
            .keybindings
            .iter()
            .filter_map(|kb| canonical_chord(&kb.key))
            .collect();

        let mut added_count = 0;
        for default_kb in default_keybindings {
            if existing_actions.contains(&default_kb.action) {
                continue;
            }

            // A new or moved default never takes a chord the user's config
            // already binds to another action — otherwise an upgrading user
            // silently gains a duplicate chord (B20/B23). Inserting into the
            // claimed set returns false when the chord is taken.
            if let Some(canonical) = canonical_chord(&default_kb.key) {
                if !claimed_chords.insert(canonical) {
                    log::warn!(
                        "Not adding default keybinding {} -> {}: the chord is already bound by \
                         another action in this config",
                        default_kb.key,
                        default_kb.action
                    );
                    continue;
                }
            } else {
                // Uncanonicalizable chord: still add the row so behavior
                // matches previous releases; the registry warns if the chord
                // cannot actually parse.
            }

            log::info!(
                "Adding new default keybinding: {} -> {}",
                default_kb.key,
                default_kb.action
            );
            self.keybindings.push(KeyBinding {
                key: default_kb.key.clone(),
                action: default_kb.action.clone(),
            });
            added_count += 1;
        }

        if added_count > 0 {
            log::info!(
                "Merged {} new default keybinding(s) into user config",
                added_count
            );
        }
    }

    /// Merge default status bar widgets into the user's config.
    /// Only adds widgets whose `WidgetId` doesn't already exist in the user's widget list.
    /// This ensures new built-in widgets are available to existing users.
    pub(crate) fn merge_default_widgets(&mut self) {
        let default_widgets = crate::status_bar::default_widgets();

        let existing_ids: std::collections::HashSet<crate::status_bar::WidgetId> = self
            .status_bar
            .status_bar_widgets
            .iter()
            .map(|w| w.id.clone())
            .collect();

        let mut added_count = 0;
        for default_widget in default_widgets {
            if !existing_ids.contains(&default_widget.id) {
                log::info!(
                    "Adding new default status bar widget: {:?}",
                    default_widget.id
                );
                self.status_bar.status_bar_widgets.push(default_widget);
                added_count += 1;
            }
        }

        if added_count > 0 {
            log::info!(
                "Merged {} new default status bar widget(s) into user config",
                added_count
            );
        }
    }

    /// Generate keybindings for snippets and actions that have keybindings configured.
    ///
    /// This method adds or updates keybindings for snippets and actions in the keybindings list,
    /// using the format `snippet:<id>` for snippets and `action:<id>` for actions.
    /// If a keybinding for a snippet/action already exists, it will be updated with the new key.
    pub fn generate_snippet_action_keybindings(&mut self) {
        use crate::config::KeyBinding;

        // Track actions we've seen to remove stale keybindings later
        let mut seen_actions = std::collections::HashSet::new();
        let mut added_count = 0;
        let mut updated_count = 0;

        // Generate keybindings for snippets
        for snippet in &self.snippets {
            if let Some(key) = &snippet.keybinding {
                let action = format!("snippet:{}", snippet.id);
                seen_actions.insert(action.clone());

                if !key.is_empty() && snippet.enabled && snippet.keybinding_enabled {
                    // Check if this action already has a keybinding
                    if let Some(existing) =
                        self.keybindings.iter_mut().find(|kb| kb.action == action)
                    {
                        // Update existing keybinding if the key changed
                        if existing.key != *key {
                            log::info!(
                                "Updating keybinding for snippet '{}': {} -> {} (was: {})",
                                snippet.title,
                                key,
                                action,
                                existing.key
                            );
                            existing.key = key.clone();
                            updated_count += 1;
                        }
                    } else {
                        // Add new keybinding
                        log::info!(
                            "Adding keybinding for snippet '{}': {} -> {} (enabled={}, keybinding_enabled={})",
                            snippet.title,
                            key,
                            action,
                            snippet.enabled,
                            snippet.keybinding_enabled
                        );
                        self.keybindings.push(KeyBinding {
                            key: key.clone(),
                            action,
                        });
                        added_count += 1;
                    }
                } else if !key.is_empty() {
                    log::info!(
                        "Skipping keybinding for snippet '{}': {} (enabled={}, keybinding_enabled={})",
                        snippet.title,
                        key,
                        snippet.enabled,
                        snippet.keybinding_enabled
                    );
                }
            }
        }

        // Generate keybindings for actions
        for action_config in &self.actions {
            if let Some(key) = action_config.keybinding() {
                let action = format!("action:{}", action_config.id());
                let prefix_only = !self.custom_action_prefix_key.trim().is_empty()
                    && action_config.prefix_char().is_none()
                    && action_config.single_char_keybinding_follow_up().is_some();

                if prefix_only {
                    log::info!(
                        "Skipping global keybinding for action '{}': {} is a prefix follow-up",
                        action_config.title(),
                        key
                    );
                    continue;
                }
                seen_actions.insert(action.clone());

                if !key.is_empty() && action_config.keybinding_enabled() {
                    // Check if this action already has a keybinding
                    if let Some(existing) =
                        self.keybindings.iter_mut().find(|kb| kb.action == action)
                    {
                        // Update existing keybinding if the key changed
                        if existing.key != key {
                            log::info!(
                                "Updating keybinding for action '{}': {} -> {} (was: {})",
                                action_config.title(),
                                key,
                                action,
                                existing.key
                            );
                            existing.key = key.to_string();
                            updated_count += 1;
                        }
                    } else {
                        // Add new keybinding
                        log::info!(
                            "Adding keybinding for action '{}': {} -> {} (keybinding_enabled={})",
                            action_config.title(),
                            key,
                            action,
                            action_config.keybinding_enabled()
                        );
                        self.keybindings.push(KeyBinding {
                            key: key.to_string(),
                            action,
                        });
                        added_count += 1;
                    }
                } else if !key.is_empty() {
                    log::info!(
                        "Skipping keybinding for action '{}': {} (keybinding_enabled={})",
                        action_config.title(),
                        key,
                        action_config.keybinding_enabled()
                    );
                }
            }
        }

        // Remove stale keybindings for snippets that no longer have keybindings or are disabled
        let original_len = self.keybindings.len();
        self.keybindings.retain(|kb| {
            // Keep if it's not a snippet/action keybinding
            if !kb.action.starts_with("snippet:") && !kb.action.starts_with("action:") {
                return true;
            }
            // Keep if we saw it during our scan
            seen_actions.contains(&kb.action)
        });
        let removed_count = original_len - self.keybindings.len();

        if added_count > 0 || updated_count > 0 || removed_count > 0 {
            log::info!(
                "Snippet/Action keybindings: {} added, {} updated, {} removed",
                added_count,
                updated_count,
                removed_count
            );
        }
    }
}

#[cfg(test)]
mod migration_tests {
    use super::*;

    fn config_with(keybindings: &[(&str, &str)]) -> Config {
        Config {
            keybindings: keybindings
                .iter()
                .map(|(key, action)| KeyBinding {
                    key: key.to_string(),
                    action: action.to_string(),
                })
                .collect(),
            ..Config::default()
        }
    }

    fn bound_chord(config: &Config, action: &str) -> Option<String> {
        config
            .keybindings
            .iter()
            .find(|kb| kb.action == action)
            .map(|kb| kb.key.clone())
    }

    /// Every canonical chord appears at most once across the binding list.
    fn no_duplicate_chords(config: &Config) -> bool {
        let mut seen = HashSet::new();
        config
            .keybindings
            .iter()
            .filter_map(|kb| canonical_chord(&kb.key))
            .all(|chord| seen.insert(chord))
    }

    #[test]
    fn canonical_chord_folds_synonyms_and_order() {
        assert_eq!(
            canonical_chord("Ctrl+Shift+T"),
            canonical_chord("shift+control+t")
        );
        assert_eq!(
            canonical_chord("CmdOrCtrl+Shift+P"),
            canonical_chord("Shift+CmdOrCtrl+P")
        );
        assert_eq!(canonical_chord("Alt+F5"), canonical_chord("Option+F5"));
        assert_eq!(canonical_chord("Cmd+O"), canonical_chord("command+O"));
        assert_eq!(
            canonical_chord("CmdOrCtrl+O"),
            if cfg!(target_os = "macos") {
                canonical_chord("Cmd+O")
            } else {
                canonical_chord("Ctrl+O")
            }
        );
    }

    #[test]
    fn canonical_chord_rejects_keyless_and_multi_key() {
        assert_eq!(canonical_chord("Ctrl+Shift+"), None);
        assert_eq!(canonical_chord("Ctrl"), None);
        assert_eq!(canonical_chord("Ctrl+D+T"), None);
        assert!(canonical_chord("Ctrl+D").is_some());
    }

    #[test]
    fn moved_default_is_not_added_when_chord_claimed() {
        // UX.md K10's planned move: command palette claims CmdOrCtrl+Shift+P,
        // which this previous-release config already binds to the drawer.
        let mut config = config_with(&[("CmdOrCtrl+Shift+P", "toggle_profile_drawer")]);

        let future_defaults = vec![KeyBinding {
            key: "Shift+CmdOrCtrl+P".to_string(), // different spelling, same chord
            action: "command_palette".to_string(),
        }];
        config.merge_default_keybindings_from(&future_defaults);

        assert!(
            bound_chord(&config, "command_palette").is_none(),
            "a default must not claim an already-bound chord"
        );
        assert_eq!(
            bound_chord(&config, "toggle_profile_drawer"),
            Some("CmdOrCtrl+Shift+P".to_string())
        );
    }

    #[test]
    fn split_renames_resolve_to_placement_ids() {
        assert_eq!(current_action_id("split_horizontal"), "split_down");
        assert_eq!(current_action_id("split_vertical"), "split_right");
        assert_eq!(current_action_id("split_right"), "split_right");
        assert_eq!(current_action_id("new_tab"), "new_tab");

        let mut config = config_with(&[
            ("Ctrl+Shift+D", "split_horizontal"),
            ("Ctrl+Shift+E", "split_vertical"),
        ]);
        config.migrate_renamed_keybinding_actions();
        assert_eq!(
            bound_chord(&config, "split_down"),
            Some("Ctrl+Shift+D".to_string())
        );
        assert_eq!(
            bound_chord(&config, "split_right"),
            Some("Ctrl+Shift+E".to_string())
        );
    }

    #[test]
    fn renamed_action_migrates_in_place() {
        // D1's planned rename: split_horizontal -> split_down. The user's
        // chord moves to the new id; the new default is not added alongside.
        let mut config = config_with(&[("CmdOrCtrl+D", "split_horizontal")]);

        config.migrate_renamed_keybinding_actions_from(&[("split_horizontal", "split_down")]);
        assert_eq!(
            bound_chord(&config, "split_down"),
            Some("CmdOrCtrl+D".to_string())
        );
        assert!(bound_chord(&config, "split_horizontal").is_none());

        let future_defaults = vec![KeyBinding {
            key: "CmdOrCtrl+D".to_string(),
            action: "split_down".to_string(),
        }];
        config.merge_default_keybindings_from(&future_defaults);
        assert!(
            no_duplicate_chords(&config),
            "the renamed binding must not gain a duplicate chord"
        );
        assert_eq!(
            config
                .keybindings
                .iter()
                .filter(|kb| kb.action == "split_down")
                .count(),
            1
        );
    }

    /// UX.md P2 acceptance: loading a config saved by the previous release
    /// preserves every existing binding and produces no duplicate chords.
    #[test]
    fn previous_release_config_preserves_bindings_without_duplicates() {
        let previous_release_yaml = r#"
keybindings:
  - key: CmdOrCtrl+D
    action: split_horizontal
  - key: CmdOrCtrl+Shift+P
    action: toggle_profile_drawer
  - key: CmdOrCtrl+Shift+F9
    action: my_custom_action
"#;
        let mut config: Config =
            serde_yaml_ng::from_str(previous_release_yaml).expect("fixture YAML parses");

        config.merge_default_keybindings();

        // Every previous-release binding survives on its own chord — the
        // renamed split action under its current id (T7 migration).
        assert_eq!(
            bound_chord(&config, "split_down"),
            Some("CmdOrCtrl+D".to_string())
        );
        assert!(bound_chord(&config, "split_horizontal").is_none());
        assert_eq!(
            bound_chord(&config, "toggle_profile_drawer"),
            Some("CmdOrCtrl+Shift+P".to_string())
        );
        assert_eq!(
            bound_chord(&config, "my_custom_action"),
            Some("CmdOrCtrl+Shift+F9".to_string())
        );

        // And the merged result has no chord claimed twice.
        assert!(
            no_duplicate_chords(&config),
            "merged config must not contain duplicate chords"
        );

        // Missing defaults are still filled in (an action with no binding at
        // all gains the default, as before).
        assert!(bound_chord(&config, "toggle_background_shader").is_some());
    }

    /// UX.md 3.3a: the shipped defaults bind every canonical chord to exactly
    /// one action on this platform. The registry resolves a duplicate by
    /// first-wins, so a collision here would make one default silently dead.
    #[test]
    fn shipped_defaults_bind_each_chord_once() {
        let mut owner: std::collections::HashMap<String, String> = std::collections::HashMap::new();
        let mut collisions = Vec::new();
        for kb in crate::defaults::keybindings() {
            let chord = canonical_chord(&kb.key)
                .unwrap_or_else(|| panic!("default chord {:?} does not canonicalize", kb.key));
            if let Some(previous) = owner.insert(chord.clone(), kb.action.clone()) {
                collisions.push(format!("{chord}: {previous} and {}", kb.action));
            }
        }
        assert!(
            collisions.is_empty(),
            "default chords bound more than once: {collisions:#?}"
        );
    }

    /// UX.md 3.3a moved chords between actions (splits swap, resize and swap
    /// trade chords, Cmd+W becomes pane close, Cmd+Shift+T becomes reopen,
    /// Cmd+R goes back to the shell). A config saved before the move keeps
    /// every chord on its old action, and the merge adds no duplicate.
    #[cfg(target_os = "macos")]
    #[test]
    fn pre_iterm2_alignment_config_keeps_every_moved_chord() {
        let previous_release_yaml = r#"
keybindings:
  - key: CmdOrCtrl+D
    action: split_horizontal
  - key: CmdOrCtrl+Shift+D
    action: split_vertical
  - key: CmdOrCtrl+Shift+W
    action: close_pane
  - key: CmdOrCtrl+W
    action: close_window
  - key: CmdOrCtrl+Alt+Shift+Left
    action: resize_pane_left
  - key: CmdOrCtrl+Ctrl+Alt+Left
    action: swap_pane_left
  - key: CmdOrCtrl+Shift+T
    action: toggle_throughput_mode
  - key: CmdOrCtrl+Z
    action: reopen_closed_tab
  - key: CmdOrCtrl+R
    action: toggle_command_history
  - key: CmdOrCtrl+Shift+P
    action: toggle_profile_drawer
  - key: CmdOrCtrl+Alt+T
    action: toggle_tmux_session_picker
"#;
        let mut config: Config =
            serde_yaml_ng::from_str(previous_release_yaml).expect("fixture YAML parses");
        config.merge_default_keybindings();

        for (chord, action) in [
            ("CmdOrCtrl+D", "split_down"),
            ("CmdOrCtrl+Shift+D", "split_right"),
            ("CmdOrCtrl+Shift+W", "close_pane"),
            ("CmdOrCtrl+W", "close_window"),
            ("CmdOrCtrl+Alt+Shift+Left", "resize_pane_left"),
            ("CmdOrCtrl+Ctrl+Alt+Left", "swap_pane_left"),
            ("CmdOrCtrl+Shift+T", "toggle_throughput_mode"),
            ("CmdOrCtrl+Z", "reopen_closed_tab"),
            ("CmdOrCtrl+R", "toggle_command_history"),
            ("CmdOrCtrl+Shift+P", "toggle_profile_drawer"),
            ("CmdOrCtrl+Alt+T", "toggle_session_picker"),
        ] {
            let bound: Vec<&str> = config
                .keybindings
                .iter()
                .filter(|kb| canonical_chord(&kb.key) == canonical_chord(chord))
                .map(|kb| kb.action.as_str())
                .collect();
            assert_eq!(bound, vec![action], "{chord} must keep its saved action");
        }
        assert!(
            no_duplicate_chords(&config),
            "merged config must not contain duplicate chords"
        );
        // A default whose action and chord are both new still arrives.
        assert_eq!(
            bound_chord(&config, "toggle_command_palette"),
            None,
            "Cmd+Shift+P is claimed by the saved drawer binding, so the palette \
             default must not take it"
        );
        assert_eq!(
            bound_chord(&config, "close_tab"),
            Some("CmdOrCtrl+Alt+W".to_string())
        );
    }

    /// Same guarantee for the Linux/Windows K1-family moves.
    #[cfg(not(target_os = "macos"))]
    #[test]
    fn pre_k1_alignment_config_keeps_every_moved_chord() {
        let previous_release_yaml = r#"
keybindings:
  - key: Ctrl+Shift+D
    action: split_horizontal
  - key: Ctrl+Shift+E
    action: split_vertical
  - key: Ctrl+Shift+X
    action: close_pane
  - key: Ctrl+Shift+W
    action: close_tab
  - key: Alt+Shift+Left
    action: swap_pane_left
  - key: Ctrl+Shift+P
    action: toggle_profile_drawer
"#;
        let mut config: Config =
            serde_yaml_ng::from_str(previous_release_yaml).expect("fixture YAML parses");
        config.merge_default_keybindings();

        for (chord, action) in [
            ("Ctrl+Shift+D", "split_down"),
            ("Ctrl+Shift+E", "split_right"),
            ("Ctrl+Shift+X", "close_pane"),
            ("Ctrl+Shift+W", "close_tab"),
            ("Alt+Shift+Left", "swap_pane_left"),
            ("Ctrl+Shift+P", "toggle_profile_drawer"),
        ] {
            let bound: Vec<&str> = config
                .keybindings
                .iter()
                .filter(|kb| canonical_chord(&kb.key) == canonical_chord(chord))
                .map(|kb| kb.action.as_str())
                .collect();
            assert_eq!(bound, vec![action], "{chord} must keep its saved action");
        }
        assert!(
            no_duplicate_chords(&config),
            "merged config must not contain duplicate chords"
        );
        assert_eq!(bound_chord(&config, "toggle_command_palette"), None);
    }

    /// UX.md K27/B20: a `pass_to_terminal` row claims its chord, so the
    /// default merge must not resurrect a default on that chord, and the row
    /// itself round-trips through YAML (restart survival).
    #[test]
    fn pass_to_terminal_row_survives_merge_and_yaml_round_trip() {
        let yaml = r#"
keybindings:
  - key: Alt+1
    action: pass_to_terminal
"#;
        let mut config: Config = serde_yaml_ng::from_str(yaml).expect("yaml parses");
        assert_eq!(
            bound_chord(&config, "pass_to_terminal"),
            Some("Alt+1".to_string())
        );

        let defaults = vec![KeyBinding {
            key: "Alt+1".to_string(),
            action: "switch_to_tab_1".to_string(),
        }];
        config.merge_default_keybindings_from(&defaults);
        assert!(
            bound_chord(&config, "switch_to_tab_1").is_none(),
            "a chord claimed by pass_to_terminal must not gain its default back"
        );
        assert_eq!(
            bound_chord(&config, "pass_to_terminal"),
            Some("Alt+1".to_string())
        );

        let rewritten = serde_yaml_ng::to_string(&config).expect("yaml serializes");
        let reloaded: Config = serde_yaml_ng::from_str(&rewritten).expect("yaml reloads");
        assert_eq!(
            bound_chord(&reloaded, "pass_to_terminal"),
            Some("Alt+1".to_string())
        );
    }

    /// UX.md D3: an upgrading Linux/Windows config still holding the old
    /// shader-toggle chord moves it to Ctrl+Alt+B, freeing Ctrl+Shift+B for
    /// the leader; nothing else about the config changes.
    #[test]
    fn an_old_default_chord_moves_to_its_new_default() {
        let mut config = config_with(&[
            ("Ctrl+Shift+B", "toggle_background_shader"),
            ("Ctrl+Shift+U", "toggle_cursor_shader"),
        ]);
        config.migrate_moved_default_chords_from(MOVED_DEFAULT_CHORDS);
        assert_eq!(
            bound_chord(&config, "toggle_background_shader").as_deref(),
            Some("Ctrl+Alt+B")
        );
        assert_eq!(
            bound_chord(&config, "toggle_cursor_shader").as_deref(),
            Some("Ctrl+Shift+U")
        );
        assert!(no_duplicate_chords(&config));
    }

    /// A user who rebound the toggle, or who already uses the new chord for
    /// something else, keeps their binding.
    #[test]
    fn a_moved_chord_never_overrides_a_user_choice() {
        let mut rebound = config_with(&[("Ctrl+Alt+S", "toggle_background_shader")]);
        rebound.migrate_moved_default_chords_from(MOVED_DEFAULT_CHORDS);
        assert_eq!(
            bound_chord(&rebound, "toggle_background_shader").as_deref(),
            Some("Ctrl+Alt+S")
        );

        let mut taken = config_with(&[
            ("Ctrl+Shift+B", "toggle_background_shader"),
            ("Ctrl+Alt+B", "toggle_fps_overlay"),
        ]);
        taken.migrate_moved_default_chords_from(MOVED_DEFAULT_CHORDS);
        assert_eq!(
            bound_chord(&taken, "toggle_background_shader").as_deref(),
            Some("Ctrl+Shift+B"),
            "the new chord is claimed, so the row stays where it was"
        );
    }

    /// The leader default is never also a registry default: a binding on
    /// the leader chord would race the leader for the key.
    #[test]
    fn no_default_keybinding_claims_the_leader_chord() {
        let leader = canonical_chord(&crate::defaults::leader_key()).expect("leader parses");
        let config = Config::default();
        let clash: Vec<&KeyBinding> = config
            .keybindings
            .iter()
            .filter(|kb| canonical_chord(&kb.key).as_deref() == Some(leader.as_str()))
            .collect();
        assert!(
            clash.is_empty(),
            "defaults bind the leader chord: {clash:?}"
        );
    }
}