gwm-cli 1.6.1

git worktree manager — TUI + CLI, native libgit2, per-repo bootstrap
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
//! Settings panel modal state (issue #232; editable in #279).
//!
//! Started life as a read-only Configuration overlay (issue #232): the
//! scroll cursor plus the owned, already-resolved [`crate::config::ConfigRow`]
//! snapshot the renderer paints. Issue #279 turns it into an editable
//! **Settings** panel — herdr-style — without dropping that read-only view:
//!
//! - **Tabs** ([`SettingsTab`]) split the surface into the editable `Theme`
//!   and `Tui` categories plus the read-only `All` resolved-config view.
//! - **A layer selector** ([`SettingsLayer`]) chooses whether an edit lands
//!   in the per-project `.gwm.toml` or the user-global `config.toml`.
//! - **Fields** ([`SettingField`]) are real toggles / choices / numeric
//!   inputs, resolved live against the loaded [`crate::config::Config`].
//!
//! The state here stays pure (no I/O): navigation, selection and the input
//! edit buffer live here and are unit-tested ratatui-free; the actual write
//! (`config_cli::set_value_at`) and the apply-live reload are orchestrated
//! by [`crate::tui::App`]. Scroll mirrors the help / Command Logs overlays:
//! the cursor lives here, `max_scroll` / `max_x_scroll` are republished by
//! the renderer each frame against the live viewport.

use crate::config::{ClipboardMode, Config, ConfigRow, ConfigSource, SidebarOrientation, SidebarPosition};
use crate::tui::keymap::{Action, KeyStroke, Keymap};
use crate::tui::modal_keymap::{ModalAction, ModalKeymap};

/// The Settings categories, in tab order. `Theme`, `Worktree`, `Tui` and
/// `Keys` are editable; `All` is the read-only resolved-config view (the
/// pre-#279 panel).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SettingsTab {
  /// Theme preset selection (editable).
  #[default]
  Theme,
  /// Worktree naming knobs: base dir + path / branch patterns.
  Worktree,
  /// TUI behaviour knobs: sidebar side, open mode + commands, confirm
  /// countdown.
  Tui,
  /// Keymap editor (issue #294): every global action + modal verb, rebound
  /// via live keystroke capture. Rows are dynamic ([`KeyRow`]), not the
  /// `&'static [SettingField]` the other editable tabs use.
  Keys,
  /// The full resolved config, read-only with source attribution.
  All,
}

impl SettingsTab {
  /// Tabs in display order — the navigation cycle.
  pub const ALL: [SettingsTab; 5] = [
    SettingsTab::Theme,
    SettingsTab::Worktree,
    SettingsTab::Tui,
    SettingsTab::Keys,
    SettingsTab::All,
  ];

  /// Short tab label shown in the header strip.
  pub fn label(self) -> &'static str {
    match self {
      SettingsTab::Theme => "Theme",
      SettingsTab::Worktree => "Worktree",
      SettingsTab::Tui => "TUI",
      SettingsTab::Keys => "Keys",
      SettingsTab::All => "All",
    }
  }

  /// The editable fields under this tab, in display order. `All` has none
  /// (it is the read-only resolved view).
  pub fn fields(self) -> &'static [SettingField] {
    match self {
      SettingsTab::Theme => &[SettingField::ThemePreset],
      SettingsTab::Worktree => &[
        SettingField::WorktreeBase,
        SettingField::WorktreePathPattern,
        SettingField::WorktreeBranchPattern,
      ],
      SettingsTab::Tui => &[
        SettingField::SidebarPosition,
        SettingField::SidebarOrientation,
        SettingField::Clipboard,
        SettingField::OpenMode,
        SettingField::ConfirmCountdown,
        SettingField::AutoRefreshSecs,
        SettingField::OpenShellCmd,
        SettingField::OpenEditorCmd,
      ],
      // The Keys tab edits dynamic [`KeyRow`]s, not static fields, and `All`
      // is read-only.
      SettingsTab::Keys | SettingsTab::All => &[],
    }
  }
}

/// What a [`KeyRow`] rebinds: a global `View::List` action ([`Action`], chords
/// allowed) or a contextual modal verb ([`ModalAction`], single-stroke).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyTarget {
  /// A global action under `[tui.keys]`.
  Global(Action),
  /// A modal verb under `[tui.keys.modal.<context>]`.
  Modal(ModalAction),
}

impl KeyTarget {
  /// The dotted `.gwm.toml` key the rebind writes (`config_cli::set_array_at`).
  pub fn config_key(self) -> String {
    match self {
      KeyTarget::Global(a) => format!("tui.keys.{}", a.slug()),
      KeyTarget::Modal(m) => format!("tui.keys.modal.{}.{}", m.context().config_path(), m.verb()),
    }
  }

  /// Modal verbs are single-stroke (issue #219); global actions accept
  /// multi-stroke chords. Drives the capture machine's accumulate-vs-commit.
  pub fn single_only(self) -> bool {
    matches!(self, KeyTarget::Modal(_))
  }

  /// Dotted `.gwm.toml` keys for any pre-#290 alias of a global action — to be
  /// stripped from a legacy config when the canonical slug is (re)written so a
  /// stale alias can't shadow the new binding (Codex #297 review). Empty for
  /// modal verbs (they have no compat aliases).
  pub fn compat_alias_keys(self) -> Vec<String> {
    match self {
      KeyTarget::Global(a) => a.compat_alias_slugs().map(|s| format!("tui.keys.{s}")).collect(),
      KeyTarget::Modal(_) => Vec::new(),
    }
  }
}

/// One row of the Keys tab: a bindable target, its display scope/label, the
/// current key(s), and the layer that sourced the binding. Built fresh on
/// panel open by [`build_key_rows`] from the live keymaps.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyRow {
  /// What this row rebinds.
  pub target: KeyTarget,
  /// `"global"` or `"modal.<context-path>"`.
  pub scope: String,
  /// The action slug (global) or context-local verb (modal).
  pub label: String,
  /// Current key(s), comma-joined (`"j, Down"`); empty when unbound.
  pub keys: String,
  /// The layer the binding came from (repo / user / default).
  pub source: ConfigSource,
}

/// Build the full Keys-tab row list: every global action (declaration order),
/// then every modal verb grouped by its context (declaration order). `source_of`
/// maps a dotted config key to its layer — the App passes the same resolved-row
/// attribution the `All` tab uses, so a hand-edited or in-TUI-set binding shows
/// the right `repo`/`user` badge and an untouched one reads `default`.
pub fn build_key_rows(keymap: &Keymap, modal: &ModalKeymap, source_of: impl Fn(&str) -> ConfigSource) -> Vec<KeyRow> {
  let mut rows = Vec::new();
  for action in Action::all() {
    let target = KeyTarget::Global(action);
    rows.push(KeyRow {
      target,
      scope: "global".to_string(),
      label: action.slug().to_string(),
      keys: keymap.keys_display(action),
      source: source_of(&target.config_key()),
    });
  }
  for action in ModalAction::all() {
    let target = KeyTarget::Modal(action);
    rows.push(KeyRow {
      target,
      scope: format!("modal.{}", action.context().config_path()),
      label: action.verb().to_string(),
      keys: modal.keys_display(action),
      source: source_of(&target.config_key()),
    });
  }
  rows
}

/// In-progress live keystroke capture for the selected [`KeyRow`] (issue
/// #294). Pure: the routing layer feeds strokes in, the App reads
/// [`Self::as_config_items`] to persist. `single_only` mirrors the target's
/// kind so the router knows whether to auto-commit (modal) or accumulate a
/// chord until the user confirms (global).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyCapture {
  /// Index into [`ConfigPanel::key_rows`] being rebound.
  pub row: usize,
  /// Modal verb → true (one stroke, auto-commit); global → false (chord).
  pub single_only: bool,
  /// The strokes captured so far, in order.
  pub pending: Vec<KeyStroke>,
}

impl KeyCapture {
  /// The TOML array elements to write: one chord, the captured strokes
  /// space-joined (`"g g"`), or an empty list when nothing was captured (an
  /// unbind). Live capture sets a single binding; alternatives stay a
  /// hand-edit.
  pub fn as_config_items(&self) -> Vec<String> {
    if self.pending.is_empty() {
      return Vec::new();
    }
    vec![self.pending.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(" ")]
  }
}

/// Which config layer an edit targets. Both are editable (issue #279):
/// `Project` writes the repo `.gwm.toml`, `Global` writes the user-level
/// `~/.config/gwm/config.toml`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SettingsLayer {
  /// The repo-local `.gwm.toml` — the default (matches `gwm config set`).
  #[default]
  Project,
  /// The user-global `~/.config/gwm/config.toml`.
  Global,
}

impl SettingsLayer {
  /// Label for the header indicator.
  pub fn label(self) -> &'static str {
    match self {
      SettingsLayer::Project => "project (.gwm.toml)",
      SettingsLayer::Global => "global (~/.config/gwm)",
    }
  }

  /// The [`ConfigSource`] an edit on this layer writes — used to decide
  /// whether the edit will actually take effect or be shadowed by a
  /// higher-precedence layer.
  pub fn source(self) -> ConfigSource {
    match self {
      SettingsLayer::Project => ConfigSource::Repo,
      SettingsLayer::Global => ConfigSource::User,
    }
  }

  /// Flip to the other layer.
  pub fn toggled(self) -> Self {
    match self {
      SettingsLayer::Project => SettingsLayer::Global,
      SettingsLayer::Global => SettingsLayer::Project,
    }
  }
}

/// How a [`SettingField`] is edited.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FieldKind {
  /// Cycle through a fixed set of values (Space / Enter advances).
  Choice,
  /// A numeric (`u32`) value edited character-by-character in a buffer.
  Uint,
  /// A free-text value edited character-by-character in a buffer.
  Text,
}

// Derived from the enums' `const fn label()` rather than restated: the choice
// string is written verbatim into `.gwm.toml`, so a list that drifted from the
// serde spelling would make the panel produce a file that no longer loads. Going
// through `label()` makes that drift impossible to express (#365).
const SIDEBAR_CHOICES: &[&str] = &[SidebarPosition::Right.label(), SidebarPosition::Left.label()];
const SIDEBAR_ORIENTATION_CHOICES: &[&str] = &[
  SidebarOrientation::Stacked.label(),
  SidebarOrientation::SideBySide.label(),
  SidebarOrientation::Auto.label(),
];
// `TuiOpenMode` has no `label()` to derive from; the round-trip test
// (`every_choice_is_a_value_the_config_can_load_back`) guards it instead.
const OPEN_MODE_CHOICES: &[&str] = &["shell", "editor", "finder"];
const CLIPBOARD_CHOICES: &[&str] = &[
  ClipboardMode::Auto.label(),
  ClipboardMode::Osc52.label(),
  ClipboardMode::Tools.label(),
];

/// One editable setting, resolved live against the loaded [`Config`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingField {
  /// `theme.preset` — cycle the built-in palettes.
  ThemePreset,
  /// `worktree.base` — the worktree base directory (text).
  WorktreeBase,
  /// `worktree.path_pattern` — the worktree dir-name pattern (text).
  WorktreePathPattern,
  /// `worktree.branch_pattern` — the branch-name pattern (text).
  WorktreeBranchPattern,
  /// `tui.sidebar_position` — left / right.
  SidebarPosition,
  /// `tui.sidebar_orientation` — stacked / side-by-side / auto.
  SidebarOrientation,
  /// `tui.clipboard` — auto / osc52 / tools.
  Clipboard,
  /// `tui.open.mode` — shell / editor / finder.
  OpenMode,
  /// `tui.confirm_countdown_secs` — numeric input.
  ConfirmCountdown,
  /// `tui.auto_refresh_secs` — numeric input, 0 disables.
  AutoRefreshSecs,
  /// `tui.open.shell_cmd` — `$SHELL` override (text).
  OpenShellCmd,
  /// `tui.open.editor_cmd` — `$EDITOR` override (text).
  OpenEditorCmd,
}

impl SettingField {
  /// Human label shown in the panel.
  pub fn label(self) -> &'static str {
    match self {
      SettingField::ThemePreset => "theme preset",
      SettingField::WorktreeBase => "base directory",
      SettingField::WorktreePathPattern => "path pattern",
      SettingField::WorktreeBranchPattern => "branch pattern",
      SettingField::SidebarPosition => "sidebar position",
      SettingField::SidebarOrientation => "sidebar layout",
      SettingField::Clipboard => "clipboard",
      SettingField::OpenMode => "open mode",
      SettingField::ConfirmCountdown => "confirm countdown (s)",
      SettingField::AutoRefreshSecs => "auto refresh (s)",
      SettingField::OpenShellCmd => "open shell cmd",
      SettingField::OpenEditorCmd => "open editor cmd",
    }
  }

  /// Dotted config key path the edit writes (`config_cli::set_value_at`).
  pub fn key_path(self) -> &'static str {
    match self {
      SettingField::ThemePreset => "theme.preset",
      SettingField::WorktreeBase => "worktree.base",
      SettingField::WorktreePathPattern => "worktree.path_pattern",
      SettingField::WorktreeBranchPattern => "worktree.branch_pattern",
      SettingField::SidebarPosition => "tui.sidebar_position",
      SettingField::SidebarOrientation => "tui.sidebar_orientation",
      SettingField::Clipboard => "tui.clipboard",
      SettingField::OpenMode => "tui.open.mode",
      SettingField::ConfirmCountdown => "tui.confirm_countdown_secs",
      SettingField::AutoRefreshSecs => "tui.auto_refresh_secs",
      SettingField::OpenShellCmd => "tui.open.shell_cmd",
      SettingField::OpenEditorCmd => "tui.open.editor_cmd",
    }
  }

  /// Whether the field is a cyclable choice, a numeric input, or free text.
  pub fn kind(self) -> FieldKind {
    match self {
      SettingField::ThemePreset
      | SettingField::SidebarPosition
      | SettingField::SidebarOrientation
      | SettingField::Clipboard
      | SettingField::OpenMode => FieldKind::Choice,
      SettingField::ConfirmCountdown | SettingField::AutoRefreshSecs => FieldKind::Uint,
      SettingField::WorktreeBase
      | SettingField::WorktreePathPattern
      | SettingField::WorktreeBranchPattern
      | SettingField::OpenShellCmd
      | SettingField::OpenEditorCmd => FieldKind::Text,
    }
  }

  fn edit_char_limit(self) -> usize {
    match self {
      SettingField::AutoRefreshSecs => 20,
      SettingField::ConfirmCountdown => 3,
      _ => 256,
    }
  }

  /// The fixed choice set for a `Choice` field. Theme presets come from the
  /// theme registry; the rest are static. Empty for non-choice fields.
  pub fn choices(self) -> &'static [&'static str] {
    match self {
      SettingField::ThemePreset => crate::tui::theme::preset_names(),
      SettingField::SidebarPosition => SIDEBAR_CHOICES,
      SettingField::SidebarOrientation => SIDEBAR_ORIENTATION_CHOICES,
      SettingField::Clipboard => CLIPBOARD_CHOICES,
      SettingField::OpenMode => OPEN_MODE_CHOICES,
      _ => &[],
    }
  }

  /// The current value as a display string, read from the resolved config.
  pub fn current(self, cfg: &Config) -> String {
    match self {
      SettingField::ThemePreset => cfg.theme.preset.clone().unwrap_or_else(|| "default".into()),
      SettingField::WorktreeBase => cfg.worktree.base.clone(),
      SettingField::WorktreePathPattern => cfg.worktree.path_pattern.clone(),
      SettingField::WorktreeBranchPattern => cfg.worktree.branch_pattern.clone(),
      SettingField::SidebarPosition => cfg.tui.sidebar_position.label().into(),
      SettingField::SidebarOrientation => cfg.tui.sidebar_orientation.label().into(),
      SettingField::Clipboard => cfg.tui.clipboard.label().into(),
      SettingField::OpenMode => match cfg.tui.open.mode {
        crate::config::TuiOpenMode::Shell => "shell".into(),
        crate::config::TuiOpenMode::Editor => "editor".into(),
        crate::config::TuiOpenMode::Finder => "finder".into(),
      },
      SettingField::ConfirmCountdown => cfg.tui.confirm_countdown_secs.to_string(),
      SettingField::AutoRefreshSecs => cfg.tui.auto_refresh_secs.to_string(),
      SettingField::OpenShellCmd => cfg.tui.open.shell_cmd.clone().unwrap_or_default(),
      SettingField::OpenEditorCmd => cfg.tui.open.editor_cmd.clone().unwrap_or_default(),
    }
  }

  /// The next value for a `Choice` field, wrapping. If the current value is
  /// not one of the choices (e.g. theme preset is `None`/"default"), the
  /// first choice is returned. `None` for `Uint` fields.
  pub fn next_choice(self, cfg: &Config) -> Option<String> {
    let choices = self.choices();
    if choices.is_empty() {
      return None;
    }
    let current = self.current(cfg);
    let idx = choices.iter().position(|c| *c == current);
    let next = match idx {
      Some(i) => choices[(i + 1) % choices.len()],
      None => choices[0],
    };
    Some(next.to_string())
  }
}

/// Owned state for the Settings overlay: the read-only resolved rows, the
/// active tab / layer / selection, the optional numeric-input edit buffer,
/// and the (vertical + horizontal) scroll cursor with renderer-published
/// bounds.
#[derive(Debug, Default)]
pub struct ConfigPanel {
  /// Resolved config rows (key, value, source) for the read-only `All` tab,
  /// grouped section-first by the renderer. Also the source-attribution
  /// lookup behind the editable tabs. Assigned by
  /// [`crate::tui::App::enter_config_panel`].
  pub rows: Vec<ConfigRow>,
  /// Active settings tab (issue #279).
  pub tab: SettingsTab,
  /// Which config layer edits target (issue #279).
  pub layer: SettingsLayer,
  /// Selected field index within the current editable tab.
  pub selected: usize,
  /// When `Some`, the numeric-input edit buffer for the selected `Uint`
  /// field; keystrokes route here until commit (Enter) or cancel (Esc).
  pub editing: Option<String>,
  /// Keys-tab rows (issue #294): every rebindable global action + modal verb
  /// with its current binding + source. Rebuilt on panel open by the App from
  /// the live keymaps; empty on the other tabs.
  pub key_rows: Vec<KeyRow>,
  /// When `Some`, a live keystroke capture is in progress on the Keys tab;
  /// strokes route into it until commit / cancel.
  pub capture: Option<KeyCapture>,
  /// Vertical scroll offset, in rows. Clamped to `max_scroll`.
  pub scroll: u16,
  /// Maximum vertical scroll offset, republished by the renderer each
  /// frame as `content_rows.saturating_sub(viewport_rows)`.
  pub max_scroll: u16,
  /// Horizontal scroll offset, in columns. Clamped to `max_x_scroll`.
  pub x_scroll: u16,
  /// Maximum horizontal scroll offset, republished by the renderer.
  pub max_x_scroll: u16,
}

impl ConfigPanel {
  /// An empty overlay at the origin.
  pub fn new() -> Self {
    Self::default()
  }

  /// The editable fields under the active tab (empty on the `All` tab).
  pub fn fields(&self) -> &'static [SettingField] {
    self.tab.fields()
  }

  /// The selected field, if the active tab has any.
  pub fn selected_field(&self) -> Option<SettingField> {
    self.fields().get(self.selected).copied()
  }

  /// The selected Keys-tab row, if the active tab is `Keys`.
  pub fn selected_key_row(&self) -> Option<&KeyRow> {
    if self.tab == SettingsTab::Keys {
      self.key_rows.get(self.selected)
    } else {
      None
    }
  }

  /// Number of selectable rows in the current tab: the static fields, or the
  /// dynamic key rows on the Keys tab.
  fn selectable_count(&self) -> usize {
    if self.tab == SettingsTab::Keys {
      self.key_rows.len()
    } else {
      self.fields().len()
    }
  }

  /// Move to the next tab, wrapping. Resets the field selection and any
  /// in-progress edit / capture so the new tab starts clean.
  pub fn next_tab(&mut self) {
    let idx = SettingsTab::ALL.iter().position(|t| *t == self.tab).unwrap_or(0);
    self.tab = SettingsTab::ALL[(idx + 1) % SettingsTab::ALL.len()];
    self.selected = 0;
    self.editing = None;
    self.capture = None;
    self.scroll = 0;
  }

  /// Move to the previous tab, wrapping. Same reset as [`Self::next_tab`].
  pub fn prev_tab(&mut self) {
    let idx = SettingsTab::ALL.iter().position(|t| *t == self.tab).unwrap_or(0);
    let len = SettingsTab::ALL.len();
    self.tab = SettingsTab::ALL[(idx + len - 1) % len];
    self.selected = 0;
    self.editing = None;
    self.capture = None;
    self.scroll = 0;
  }

  /// Flip the edit target layer (project ↔ global).
  pub fn toggle_layer(&mut self) {
    self.layer = self.layer.toggled();
  }

  /// Select the previous field / key row in the current tab (no-op while
  /// editing or capturing, or on a tab with no rows).
  pub fn select_prev(&mut self) {
    if self.editing.is_some() || self.capture.is_some() {
      return;
    }
    self.selected = self.selected.saturating_sub(1);
  }

  /// Select the next field / key row in the current tab, clamped to the last.
  pub fn select_next(&mut self) {
    if self.editing.is_some() || self.capture.is_some() {
      return;
    }
    let count = self.selectable_count();
    if count > 0 {
      self.selected = (self.selected + 1).min(count - 1);
    }
  }

  /// Begin editing the selected input field (`Uint` or `Text`), seeding the
  /// buffer with its current value. No-op if the selected field is a
  /// `Choice` (those cycle, they are not text-edited).
  pub fn begin_edit(&mut self, current: &str) {
    if matches!(
      self.selected_field().map(SettingField::kind),
      Some(FieldKind::Uint | FieldKind::Text)
    ) {
      self.editing = Some(current.to_string());
    }
  }

  /// Append a character to the edit buffer. `Uint` fields take ASCII digits
  /// only (with per-field caps); `Text` fields take any printable character
  /// (capped at 256).
  /// Returns whether the character is of the TYPE the field accepts
  /// (Codex review #456): a numeric field refuses non-digits, and a
  /// refused character is not typing — the caller lets it reach the
  /// modal resolution so a rebound verb on it still fires. A valid
  /// character arriving on a FULL buffer is a consumed no-op (`true`),
  /// never a fall-through: a digit must not suddenly cancel the edit
  /// just because the countdown hit its width limit.
  pub fn push_edit_char(&mut self, c: char) -> bool {
    let field = self.selected_field();
    let uint = matches!(field.map(SettingField::kind), Some(FieldKind::Uint));
    let limit = field.map(SettingField::edit_char_limit).unwrap_or(256);
    if let Some(buf) = self.editing.as_mut() {
      if uint {
        if !c.is_ascii_digit() {
          return false;
        }
        if buf.len() < limit {
          buf.push(c);
        }
        return true;
      }
      if c.is_control() {
        return false;
      }
      if buf.len() < limit {
        buf.push(c);
      }
      return true;
    }
    false
  }

  /// Delete the last character of the edit buffer.
  pub fn pop_edit_char(&mut self) {
    if let Some(buf) = self.editing.as_mut() {
      buf.pop();
    }
  }

  /// Cancel the in-progress edit, discarding the buffer.
  pub fn cancel_edit(&mut self) {
    self.editing = None;
  }

  /// Commit the in-progress edit, returning the raw buffer (the caller
  /// coerces an empty numeric buffer to `"0"`; an empty text buffer is a
  /// legitimate "unset" value).
  pub fn take_edit(&mut self) -> Option<String> {
    self.editing.take()
  }

  /// The source layer that currently provides `field`'s value, looked up in
  /// the resolved rows. Drives the "shadowed edit" guidance: editing the
  /// global layer for a field the repo overrides won't change the effective
  /// value (repo wins).
  pub fn field_source(&self, field: SettingField) -> Option<ConfigSource> {
    self.rows.iter().find(|r| r.key == field.key_path()).map(|r| r.source)
  }

  // ── Keys tab: live keystroke capture (issue #294) ──────────────────────

  /// Arm a live capture for the selected Keys-tab row. No-op off the Keys tab
  /// or with no row selected. The capture inherits the row's `single_only`
  /// flag so the router auto-commits a modal verb but accumulates a global
  /// chord.
  pub fn begin_capture(&mut self) {
    if self.tab != SettingsTab::Keys {
      return;
    }
    if let Some(row) = self.key_rows.get(self.selected) {
      self.capture = Some(KeyCapture {
        row: self.selected,
        single_only: row.target.single_only(),
        pending: Vec::new(),
      });
    }
  }

  /// Append a captured stroke to the in-progress capture.
  pub fn capture_push(&mut self, stroke: KeyStroke) {
    if let Some(cap) = self.capture.as_mut() {
      cap.pending.push(stroke);
    }
  }

  /// Drop the last captured stroke (Backspace during a multi-stroke capture).
  pub fn capture_pop(&mut self) {
    if let Some(cap) = self.capture.as_mut() {
      cap.pending.pop();
    }
  }

  /// Cancel the in-progress capture, discarding pending strokes.
  pub fn cancel_capture(&mut self) {
    self.capture = None;
  }

  /// Commit the in-progress capture, returning it for the App to persist.
  pub fn take_capture(&mut self) -> Option<KeyCapture> {
    self.capture.take()
  }

  /// Scroll down one row, never past the last line.
  pub fn scroll_down(&mut self) {
    self.scroll = (self.scroll + 1).min(self.max_scroll);
  }

  /// Scroll up one row, never above the top.
  pub fn scroll_up(&mut self) {
    self.scroll = self.scroll.saturating_sub(1);
  }

  /// Scroll right one column, never past the widest line.
  pub fn scroll_right(&mut self) {
    self.x_scroll = (self.x_scroll + 1).min(self.max_x_scroll);
  }

  /// Scroll left one column, never before the first.
  pub fn scroll_left(&mut self) {
    self.x_scroll = self.x_scroll.saturating_sub(1);
  }

  /// Jump to the first row (`g`).
  pub fn scroll_to_top(&mut self) {
    self.scroll = 0;
  }

  /// Jump to the last row (`G`).
  pub fn scroll_to_bottom(&mut self) {
    self.scroll = self.max_scroll;
  }

  /// Reset the cursor + selection + edit buffer to the origin, keeping the
  /// resolved rows and the active tab/layer. Called when the overlay opens.
  pub fn reset(&mut self) {
    self.scroll = 0;
    self.x_scroll = 0;
    self.selected = 0;
    self.editing = None;
    self.capture = None;
  }
}