Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

hn: the prefix and the second prefix change in Keybinds too

Tim32191a034f26
diff --git a/tui/src/config.rs b/tui/src/config.rs
index 9e40c0be5..89a2826a8 100644
--- a/tui/src/config.rs
+++ b/tui/src/config.rs
@@ -293,6 +293,26 @@ fn table_of(line: &str) -> Option<&str> {
(after.is_empty() || after.starts_with('#')).then(|| name.trim())
}
+/// [text] with the top-level `key = "value"` set ([value] None: taken out), the rest as written.
+fn with_top(text: &str, key: &str, value: Option<&str>) -> String {
+ let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
+ let end = lines.iter().position(|l| table_of(l).is_some() || is_section_header(l.trim())).unwrap_or(lines.len());
+ let line = value.map(|v| format!("{key} = {}", toml_str(v)));
+ match (lines[..end].iter().position(|l| sets(l, key)), line) {
+ (Some(i), Some(l)) => lines[i] = l,
+ (Some(i), None) => { lines.remove(i); }
+ (None, Some(l)) => {
+ // After the top's last setting (before the blank line that ends it).
+ let at = lines[..end].iter().rposition(|l| !l.trim().is_empty()).map(|i| i + 1).unwrap_or(0);
+ lines.insert(at, l);
+ }
+ (None, None) => {}
+ }
+ let mut out = lines.join("\n");
+ out.push('\n');
+ out
+}
+
/// [text] with `"entry" = "value"` in [table] (made when there is none), the rest as written.
fn with_entry(text: &str, table: &str, entry: &str, value: &str) -> String {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
@@ -324,6 +344,9 @@ fn rewrite(change: impl FnOnce(&str) -> String) -> std::io::Result<()> {
std::fs::write(p, change(&existing))
}
+/// `prefix` / `prefix2` in tui.toml ([value] None: taken out).
+pub fn write_top(key: &str, value: Option<&str>) -> std::io::Result<()> { rewrite(|t| with_top(t, key, value)) }
+
/// One key after the prefix in tui.toml's `[prefix_keys]`: its command, or "none".
pub fn write_prefix_key(key: &str, command: &str) -> std::io::Result<()> { rewrite(|t| with_entry(t, "prefix_keys", key, command)) }
@@ -539,6 +562,22 @@ mod tests {
// ── keys ──
+ /// The prefix goes into tui.toml as the panel sets it: the top's `prefix` replaced (or added,
+ /// before the first table), `prefix2` added and taken out, every other line as it was.
+ #[test]
+ fn the_prefix_chosen_in_the_panel_is_written_into_tui_toml() {
+ let text = "# mine\nprefix = \"D-b\"\n\n[look]\nfocus = \"line\"\n";
+ let t = with_top(text, "prefix", Some("C-a"));
+ assert_eq!(t, "# mine\nprefix = \"C-a\"\n\n[look]\nfocus = \"line\"\n");
+ let t = with_top(&t, "prefix2", Some("C-b"));
+ assert_eq!(t, "# mine\nprefix = \"C-a\"\nprefix2 = \"C-b\"\n\n[look]\nfocus = \"line\"\n");
+ assert_eq!(with_top(&t, "prefix2", None), "# mine\nprefix = \"C-a\"\n\n[look]\nfocus = \"line\"\n");
+ // A file with only tables: the prefix goes on top, before them.
+ assert_eq!(with_top("[look]\nfocus = \"line\"\n", "prefix", Some("C-a")), "prefix = \"C-a\"\n[look]\nfocus = \"line\"\n");
+ let v: toml::Value = t.parse().unwrap();
+ assert_eq!(v["prefix"].as_str(), Some("C-a"));
+ }
+
/// A command's key goes into tui.toml as the panel sets it: `[prefix_keys]` made or added
/// to, every other line as it was — and read back at start as written.
#[test]
diff --git a/tui/src/modal.rs b/tui/src/modal.rs
index f1d3e31d4..0a148c5a7 100644
--- a/tui/src/modal.rs
+++ b/tui/src/modal.rs
@@ -49,7 +49,7 @@ pub enum PickerKind {
Theme,
/// C-b Enter: every command by name, in the settings panel — type a few letters, Enter runs it.
Commands,
- /// Keybinds: the prefix (fixed) and each command's key after it — Enter on one changes it.
+ /// Keybinds: the prefixes and each command's key after them — Enter on one changes it.
Keybinds,
/// A task routed to a harness; [voice]: the dial's spoken task it answers.
Route { text: String, voice: Option<String> },
@@ -561,12 +561,16 @@ pub const KEYBINDS: &[(&str, &str, &str)] = &[
("Detach", "detach-client", "General"),
];
-/// The Keybinds panel: the prefix (fixed here: tui.toml's), then each command with its key now
-/// (or —). Enter on one: the next key you press is it.
+/// The Keybinds panel: the prefix and the second one, then each command with its key now (or —).
+/// Enter on one: the next key you press is it.
pub fn keybind_rows(app: &App) -> Vec<Row> {
let prefix = crate::keys::name(&app.keymap.prefix);
- let fixed = Row::new("prefix", "Prefix").detail(vec![span("the key before every command — set in tui.toml", fg(theme::MUTED))]).right(format!("{prefix} (fixed)"));
- std::iter::once(fixed).chain(KEYBINDS.iter().enumerate().map(|(i, (title, runs, group))| {
+ let prefixes = [
+ Row::new("prefix", "Prefix").detail(vec![span("the key before every command — Enter changes it", fg(theme::MUTED))]).right(prefix.clone()).group("Prefix"),
+ Row::new("prefix2", "Second prefix").detail(vec![span("one more, for a terminal that keeps ⌘ keys", fg(theme::MUTED))])
+ .right(app.keymap.prefix2.map(|c| crate::keys::name(&c)).unwrap_or_else(|| "none".into())).group("Prefix"),
+ ];
+ prefixes.into_iter().chain(KEYBINDS.iter().enumerate().map(|(i, (title, runs, group))| {
let key = key_running(app, runs).map(|c| format!("{prefix} {}", crate::keys::name(&c))).unwrap_or_else(|| "—".into());
Row::new(format!("key:{i}"), *title).right(key).group(*group)
})).collect()
@@ -859,24 +863,47 @@ mod theme_row_tests {
fn right(app: &App, title: &str) -> String { keybind_rows(app).into_iter().find(|r| r.label == title).map(|r| r.right).unwrap() }
- /// Keybinds: the prefix first — fixed, information only — then the commands grouped with
- /// their keys now. Appearance has no keys section.
+ /// Keybinds: the prefix and the second one first, then the commands grouped with their keys
+ /// now. Appearance has no keys section.
#[test]
- fn keybinds_are_the_fixed_prefix_then_every_command_grouped() {
- let mut app = app();
+ fn keybinds_are_the_prefixes_then_every_command_grouped() {
+ let app = app();
let rows = keybind_rows(&app);
- assert_eq!((rows[0].id.as_str(), rows[0].label.as_str(), rows[0].right.as_str()), ("prefix", "Prefix", "C-b (fixed)"));
- assert!(rows.iter().all(|r| !r.id.starts_with("prefix2")), "no second prefix row");
+ assert_eq!((rows[0].id.as_str(), rows[0].label.as_str(), rows[0].right.as_str()), ("prefix", "Prefix", "C-b"));
+ assert_eq!((rows[1].id.as_str(), rows[1].right.as_str()), ("prefix2", "none"));
let mut groups: Vec<String> = Vec::new();
for g in rows.iter().filter_map(|r| r.group.clone()) { if groups.last() != Some(&g) { groups.push(g) } }
- assert_eq!(groups, ["Navigation", "Panes", "Swarms (windows)", "Harnesses", "General"]);
+ assert_eq!(groups, ["Prefix", "Navigation", "Panes", "Swarms (windows)", "Harnesses", "General"]);
assert_eq!(right(&app, "Split right"), "C-b %");
- // Enter on the prefix: said where it is set, nothing waits for a key.
- assert!(crate::settings::set_key(&mut app, "prefix", "").is_some_and(|s| s.contains("tui.toml")));
- assert!(app.capturing.is_none());
assert!(theme_sections(&app).iter().all(|r| r.id != "section:keys") && theme_options(&app, "keys").is_empty());
}
+ /// The prefix changes in the panel: Enter, then the key — which needs Ctrl, ⌥ or ⌘ (a plain
+ /// key would be lost to typing). The second prefix too; ⌫ leaves none. Both saved to tui.toml.
+ #[test]
+ fn the_prefix_changes_to_a_key_with_a_modifier() {
+ let mut app = app();
+ assert!(crate::settings::set_key(&mut app, "prefix", "").is_some_and(|s| s.contains("press")));
+ for code in [KeyCode::Char('a'), KeyCode::Enter, KeyCode::Char('1')] {
+ assert!(press(&mut app, code, KeyModifiers::NONE).contains("needs Ctrl"), "{code:?} refused");
+ assert!(app.capturing.is_some(), "still waiting");
+ }
+ assert_eq!(press(&mut app, KeyCode::Char('a'), KeyModifiers::CONTROL), "Prefix: C-a — saved to tui.toml");
+ assert_eq!(crate::keys::name(&app.keymap.prefix), "C-a");
+ assert!(app.capturing.is_none());
+ // The second prefix, then none.
+ let _ = crate::settings::set_key(&mut app, "prefix2", "");
+ assert!(press(&mut app, KeyCode::Char('b'), KeyModifiers::CONTROL).starts_with("Second prefix: C-b"));
+ assert_eq!(app.keymap.prefix2.map(|c| crate::keys::name(&c)).as_deref(), Some("C-b"));
+ let _ = crate::settings::set_key(&mut app, "prefix2", "");
+ assert_eq!(press(&mut app, KeyCode::Backspace, KeyModifiers::NONE), "Second prefix: none — saved to tui.toml");
+ assert_eq!(app.keymap.prefix2, None);
+ // Esc: unchanged.
+ let _ = crate::settings::set_key(&mut app, "prefix", "");
+ assert_eq!(press(&mut app, KeyCode::Esc, KeyModifiers::NONE), "Unchanged");
+ assert_eq!(crate::keys::name(&app.keymap.prefix), "C-a");
+ }
+
/// A key chosen is the command's: its old key given up, the command in full kept (Rename
/// swarm still asks for the name).
#[test]
diff --git a/tui/src/settings.rs b/tui/src/settings.rs
index 0f513c41b..039a96bb1 100644
--- a/tui/src/settings.rs
+++ b/tui/src/settings.rs
@@ -102,18 +102,21 @@ pub fn back_to_commands_at(app: &App, picker: &mut Picker, at: &str) {
/// Put the cursor on the row [id] (where the filter shows it).
pub fn cursor_to(picker: &mut Picker, id: &str) { picker.select(id) }
-// ── keys: a command's key, chosen in the panel ───────────────────────────────────
+// ── keys: the prefix and a command's key, chosen in the panel ────────────────────
-/// What the next key becomes: [command]'s key after the prefix. [pending]: a key that runs
-/// another command, pressed once — the same key again replaces it.
+/// What the next key becomes: the prefix ([second]: the second one), or [command]'s key after the
+/// prefix. [pending]: a key that runs another command, pressed once — the same key again replaces it.
#[derive(Clone, Debug)]
-pub enum Capture { Command { command: String, title: String, own: bool, pending: Option<crate::keys::Chord> } }
+pub enum Capture {
+ Prefix { second: bool },
+ Command { command: String, title: String, own: bool, pending: Option<crate::keys::Chord> },
+}
const PRESS: &str = "press a key · Esc cancels";
const AGAIN: &str = "press another key · Esc cancels";
-/// A Keybinds row chosen: a command's (`key`, its index) waits for the next key pressed; the
-/// prefix's says where it is set. None: not a Keybinds row.
+/// A Keybinds row chosen: the next key pressed becomes the prefix (`prefix`, `prefix2`) or a
+/// command's (`key`, its index). None: not a Keybinds row.
pub fn set_key(app: &mut App, knob: &str, value: &str) -> Option<String> {
match knob {
"key" => {
@@ -121,11 +124,41 @@ pub fn set_key(app: &mut App, knob: &str, value: &str) -> Option<String> {
app.capturing = Some(Capture::Command { command: runs.to_string(), title: title.to_string(), own: true, pending: None });
Some(format!("{}: {PRESS}", title.trim_end_matches('…')))
}
- "prefix" => Some(format!("The prefix is {} — set `prefix` in tui.toml to change it", crate::keys::name(&app.keymap.prefix))),
+ "prefix" => { app.capturing = Some(Capture::Prefix { second: false }); Some(format!("Prefix: press the new one — Ctrl, ⌥ or ⌘ with a key · Esc cancels")) }
+ "prefix2" => { app.capturing = Some(Capture::Prefix { second: true }); Some(format!("Second prefix: press it — Ctrl, ⌥ or ⌘ with a key · ⌫ none · Esc cancels")) }
_ => None,
}
}
+/// The prefix (or the second one, [chord] None: none) set as `set -g prefix` sets it — every hn
+/// window takes it — and written to tui.toml, so it is the prefix the next time hn starts too.
+fn apply_prefix(app: &mut App, second: bool, chord: Option<crate::keys::Chord>) -> String {
+ let option = if second { "prefix2" } else { "prefix" };
+ let name = chord.map(|c| crate::keys::name(&c)).unwrap_or_else(|| "None".to_string());
+ crate::commands::execute(app, &format!("set -g {option} {}", crate::tmuxconf::quote_word(&name)));
+ app.server_dirty = true;
+ let saved = crate::config::write_top(option, chord.is_some().then_some(name.as_str()));
+ let what = if second { "Second prefix" } else { "Prefix" };
+ let shown = if chord.is_some() { name } else { "none".into() };
+ match saved { Ok(()) => format!("{what}: {shown} — saved to tui.toml"), Err(e) => format!("{what}: {shown} — could not write tui.toml: {e}") }
+}
+
+/// The key pressed for a prefix: one with Ctrl, ⌥ or ⌘ (a plain key would be lost to typing);
+/// for the second, ⌫ is none. (Said, and whether it is still waiting.)
+fn captured_prefix(app: &mut App, second: bool, key: crossterm::event::KeyEvent) -> (String, bool) {
+ use crossterm::event::{KeyCode, KeyModifiers};
+ let chord = crate::keys::of(&key);
+ let name = crate::keys::name(&chord);
+ if key.code == KeyCode::Esc && key.modifiers.is_empty() { return ("Unchanged".into(), false) }
+ if second && key.code == KeyCode::Backspace && key.modifiers.is_empty() { return (apply_prefix(app, true, None), false) }
+ if !key.modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER | KeyModifiers::META) {
+ return (format!("{name}: a prefix needs Ctrl, ⌥ or ⌘ — like C-a · Esc cancels"), true)
+ }
+ if second && chord == app.keymap.prefix { return (format!("{name} is the prefix already — {AGAIN}"), true) }
+ if !second && Some(chord) == app.keymap.prefix2 { return (format!("{name} is the second prefix — {AGAIN}"), true) }
+ (apply_prefix(app, second, Some(chord)), false)
+}
+
/// Alt-k on a command in the command panel: its key is the next key you press. A command with
/// no key of its own to run (one that needs words) says so.
pub fn capture_for_row(app: &mut App, picker: &mut Picker) {
@@ -143,7 +176,15 @@ pub fn capture_for_row(app: &mut App, picker: &mut Picker) {
/// keeps it; else it becomes the command's. What happened is said in the panel, whose rows show it.
pub fn captured(app: &mut App, key: crossterm::event::KeyEvent) {
use crossterm::event::KeyCode;
- let Some(Capture::Command { command, title, own, pending }) = app.capturing.take() else { return };
+ let (command, title, own, pending) = match app.capturing.take() {
+ Some(Capture::Command { command, title, own, pending }) => (command, title, own, pending),
+ Some(Capture::Prefix { second }) => {
+ let (said, waiting) = captured_prefix(app, second, key);
+ if waiting { app.capturing = Some(Capture::Prefix { second }) }
+ return show_captured(app, said);
+ }
+ None => return,
+ };
let chord = crate::keys::of(&key);
let name = crate::keys::name(&chord);
let prefix = crate::keys::name(&app.keymap.prefix);
@@ -159,7 +200,11 @@ pub fn captured(app: &mut App, key: crossterm::event::KeyEvent) {
}
else { (rebind(app, &command, &title, own, chord), None) };
app.capturing = next;
- // The panel's rows again, with the key as it is now.
+ show_captured(app, said)
+}
+
+/// The panel's rows again, with the keys as they are now, and [said] in it.
+fn show_captured(app: &mut App, said: String) {
if let Some(crate::modal::Modal::Picker { kind, picker }) = app.modal.take() {
let mut picker = picker;
let at = picker.current_id();
diff --git a/tui/src/ui.rs b/tui/src/ui.rs
index 0b6fa1102..15e785a96 100644
--- a/tui/src/ui.rs
+++ b/tui/src/ui.rs
@@ -3108,12 +3108,14 @@ mod theme_render_tests {
let Some(Modal::Picker { kind, picker }) = &app.modal else { panic!("closed") };
assert!(matches!(kind, PickerKind::Keybinds) && picker.from_commands);
assert_eq!(picker.screen_area.get(), at, "the panel stayed where it was");
- assert!(s.contains("Keybinds") && s.contains("Prefix") && s.contains("C-b (fixed)") && s.contains("Split right") && s.contains("Navigation"), "{s}");
- assert!(!s.contains("Preview") && !s.contains("Appearance") && !s.contains("Second prefix"), "{s}");
- // The prefix: information only.
+ assert!(s.contains("Keybinds") && s.contains("Prefix") && s.contains("Second prefix") && s.contains("Split right") && s.contains("Navigation"), "{s}");
+ assert!(!s.contains("Preview") && !s.contains("Appearance"), "{s}");
+ // The prefix: Enter waits for the new one; Esc leaves it.
assert_eq!(picker.current_id().as_deref(), Some("prefix"));
key(&mut app, KeyCode::Enter);
- assert!(app.capturing.is_none() && said(&app).contains("tui.toml"), "{}", said(&app));
+ assert!(app.capturing.is_some() && said(&app).starts_with("Prefix: press"), "{}", said(&app));
+ key(&mut app, KeyCode::Esc);
+ assert!(app.capturing.is_none() && said(&app) == "Unchanged", "{}", said(&app));
// Split right onto n (Next swarm's): named first, replaced on the second press.
if let Some(Modal::Picker { picker, .. }) = &mut app.modal { let i = crate::modal::KEYBINDS.iter().position(|k| k.0 == "Split right").unwrap(); picker.select(&format!("key:{i}")) }
key(&mut app, KeyCode::Enter);
diff --git a/tui/tests/keybinds.py b/tui/tests/keybinds.py
index 74f786485..b51aae61e 100644
--- a/tui/tests/keybinds.py
+++ b/tui/tests/keybinds.py
@@ -80,9 +80,9 @@ try:
start()
started = True
- # C-b Enter → keyb → Enter: Keybinds, its own panel, the prefix first and fixed.
+ # C-b Enter → keyb → Enter: Keybinds, its own panel, the prefixes first.
keys('C-b', 'Enter'); shows('Commands')
- type_text('keyb'); keys('Enter'); shows('(fixed)')
+ type_text('keyb'); keys('Enter'); shows('Second prefix')
s = screen()
assert 'Keybinds' in s and 'Split right' in s and 'Preview' not in s and 'Appearance' not in s, s
# Split right → Enter → h.
@@ -91,7 +91,7 @@ try:
keys('h'); shows('saved to tui.toml')
assert any('Split right' in l and 'C-b h' in l for l in screen().splitlines()), screen()
# Esc back to Commands, Esc closes.
- keys('Escape'); shows('Commands'); gone('(fixed)')
+ keys('Escape'); shows('Commands'); gone('Second prefix')
keys('Escape'); gone('Commands')
toml = TOML.read_text()
assert '[prefix_keys]' in toml and '"h" = "split-window -h"' in toml and '"%" = "none"' in toml, toml
@@ -112,6 +112,24 @@ try:
assert panes() == before + 1, 'C-b % still free after a restart'
print('PASS Keybinds: after a restart C-b h still splits', flush=True)
+ # The prefix: Keybinds → Prefix → Enter → C-a. A plain key is refused; C-a is saved to tui.toml.
+ keys('C-b', 'Enter'); shows('Commands')
+ type_text('keyb'); keys('Enter'); shows('Second prefix')
+ keys('Enter'); shows('Prefix: press')
+ keys('q'); shows('a prefix needs Ctrl')
+ keys('C-a'); shows('Prefix: C-a')
+ keys('Escape'); keys('Escape'); gone('Commands')
+ toml = TOML.read_text()
+ assert 'prefix = "C-a"' in toml, toml
+ before = panes()
+ keys('C-a', 'h'); wait(lambda: panes() == before + 1, 'C-a h splits')
+ hn('kill-server', ok=False); tmux('kill-server', ok=False); started = False
+ time.sleep(.3)
+ start(); started = True
+ before = panes()
+ keys('C-a', 'h'); wait(lambda: panes() == before + 1, 'C-a h splits after a restart')
+ print('PASS Keybinds: the prefix changed to C-a in the panel, saved, and still C-a after a restart', flush=True)
+
finally:
try:
if started: