croft-software 0.2.182

VSCode-style TUI written in Rust
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
//! Ghostty keyboard integration for croft.
//!
//! Ghostty consults its own keybinding layer *before* it encodes a key for the
//! foreground application, so a default bind like `cmd+t=new_tab` swallows the
//! chord and croft never sees it, no matter that croft has already negotiated
//! the kitty keyboard protocol. iTerm2 has the same problem and croft solves it
//! by relocating iTerm2's menu items and installing `GlobalKeyMap` forwarders
//! (see [`crate::iterm2`]); the Ghostty equivalent is a block of `keybind`
//! lines in Ghostty's config that re-emit each chord as the same CSI-u sequence
//! via Ghostty's `csi:` action. The byte payloads are reused verbatim from
//! [`crate::iterm2::payloads`] so croft receives byte-identical input on both
//! terminals.
//!
//! Ghostty's `csi:` action sends a CSI sequence *without* the `ESC [` header,
//! so croft's `ESC [ 116 ; 9 u` (Cmd+T) becomes the keybind `cmd+t=csi:116;9u`.
//! Modifier and key spellings (`cmd`/`shift`/`ctrl`/`alt`, `arrow_left`,
//! `f12`, `enter`, and literal codepoints for printable keys) are taken from
//! Ghostty's trigger parser.

use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

use crate::iterm2::payloads as pl;

/// The folders Ghostty reads its config from, under `$XDG_CONFIG_HOME`
/// (default `~/.config`) on every OS and, on macOS, under `~`, and the file
/// names it reads in each, the current one first (#1439).
const XDG_DIR: &str = "ghostty";
const APP_SUPPORT_DIR: &str = "Library/Application Support/com.mitchellh.ghostty";
/// In the order Ghostty loads them from one folder: the legacy name first,
/// then `config.ghostty`, whose values win.
const CONFIG_NAMES: [&str; 2] = ["config", "config.ghostty"];

/// Marker lines that fence croft's managed keybind block inside the user's
/// Ghostty config. Re-running setup replaces everything between them, leaving
/// the rest of the file untouched.
const BLOCK_BEGIN: &str = "# >>> croft keybindings (managed by `croft setup-ghostty`) >>>";
const BLOCK_END: &str = "# <<< croft keybindings (managed by `croft setup-ghostty`) <<<";
const KEYBIND_PREFIX: &str = "keybind = ";
const CSI_ACTION: &str = "csi:";

/// Every croft chord forwarded under Ghostty, paired with the byte payload that
/// reaches croft, as `(ghostty_trigger, iterm2_csi_hex)`. This mirrors the set
/// iTerm2 forwards in [`crate::iterm2`] one-for-one. Printable keys use their
/// literal codepoint as the trigger (Ghostty accepts single-codepoint keys);
/// arrows use `arrow_left`/`arrow_right`; function keys use `f12`. Cmd+V is
/// intentionally absent on both terminals so Ghostty's native paste keeps
/// working locally and over SSH via bracketed paste. The digit chords
/// (`cmd+0`..`cmd+9`) are appended separately from [`pl::CMD_DIGIT_CHORDS`].
const CHORDS: &[(&str, &str)] = &[
    // Explorer / search chords.
    ("cmd+shift+f", pl::CMD_SHIFT_F_HEX),
    ("cmd+f", pl::CMD_F_HEX),
    ("cmd+r", pl::CMD_R_HEX),
    ("cmd+alt+r", pl::CMD_OPT_R_HEX),
    ("cmd+alt+c", pl::CMD_OPT_C_HEX),
    ("cmd+alt+m", pl::CMD_OPT_M_HEX),
    ("cmd+alt+f", pl::CMD_OPT_F_HEX),
    ("cmd+alt+enter", pl::CMD_OPT_ENTER_HEX),
    ("cmd+/", pl::CMD_SLASH_HEX),
    ("cmd+.", pl::CMD_DOT_HEX),
    ("cmd+shift+/", pl::CMD_SHIFT_SLASH_HEX),
    ("cmd+shift+enter", pl::CMD_SHIFT_ENTER_HEX),
    // Mac-style Cmd+letter editor / terminal / source-control chords.
    ("cmd+a", pl::CMD_A_HEX),
    ("cmd+c", pl::CMD_C_HEX),
    ("cmd+s", pl::CMD_S_HEX),
    ("cmd+x", pl::CMD_X_HEX),
    ("cmd+z", pl::CMD_Z_HEX),
    ("cmd+shift+z", pl::CMD_SHIFT_Z_HEX),
    ("cmd+d", pl::CMD_D_HEX),
    ("cmd+g", pl::CMD_G_HEX),
    ("cmd+k", pl::CMD_K_HEX),
    ("cmd+y", pl::CMD_Y_HEX),
    ("cmd+o", pl::CMD_O_HEX),
    ("cmd+e", pl::CMD_E_HEX),
    ("cmd+p", pl::CMD_P_HEX),
    ("cmd+w", pl::CMD_W_HEX),
    ("cmd+b", pl::CMD_B_HEX),
    // Sidebar / view jumps (Cmd+Shift+letter).
    ("cmd+shift+g", pl::CMD_SHIFT_G_HEX),
    ("cmd+shift+o", pl::CMD_SHIFT_O_HEX),
    ("cmd+shift+e", pl::CMD_SHIFT_E_HEX),
    ("cmd+shift+s", pl::CMD_SHIFT_S_HEX),
    ("cmd+shift+d", pl::CMD_SHIFT_D_HEX),
    ("cmd+shift+r", pl::CMD_SHIFT_R_HEX),
    ("cmd+shift+x", pl::CMD_SHIFT_X_HEX),
    ("cmd+shift+l", pl::CMD_SHIFT_L_HEX),
    ("cmd+shift+n", pl::CMD_SHIFT_N_HEX),
    ("cmd+shift+b", pl::CMD_SHIFT_B_HEX),
    ("cmd+shift+t", pl::CMD_SHIFT_T_HEX),
    ("cmd+shift+v", pl::CMD_SHIFT_V_HEX),
    // Terminal: new + cycle.
    ("cmd+t", pl::CMD_T_HEX),
    ("cmd+[", pl::CMD_LBRACKET_HEX),
    ("cmd+]", pl::CMD_RBRACKET_HEX),
    // Maximize terminal.
    ("ctrl+shift+j", pl::CTRL_SHIFT_J_HEX),
    // Editor: split, focus group, LSP navigation.
    ("cmd+\\", pl::CMD_BACKSLASH_HEX),
    // Go to Bracket (VS Code editor.action.jumpToBracket).
    ("cmd+shift+\\", pl::CMD_SHIFT_BACKSLASH_HEX),
    // Select to Bracket (editor.action.selectToBracket).
    ("cmd+alt+\\", pl::CMD_OPT_BACKSLASH_HEX),
    // Convert Indentation to Spaces / Tabs, Trim Final Newlines.
    ("cmd+alt+shift+s", pl::CMD_OPT_SHIFT_S_HEX),
    ("cmd+alt+shift+t", pl::CMD_OPT_SHIFT_T_HEX),
    ("cmd+alt+shift+n", pl::CMD_OPT_SHIFT_N_HEX),
    // Join Lines, Transform Upper/Lower/Title, Sort Asc/Desc, Trim Trailing.
    ("cmd+alt+shift+j", pl::CMD_OPT_SHIFT_J_HEX),
    ("cmd+alt+shift+u", pl::CMD_OPT_SHIFT_U_HEX),
    ("cmd+alt+shift+l", pl::CMD_OPT_SHIFT_L_HEX),
    ("cmd+alt+shift+c", pl::CMD_OPT_SHIFT_C_HEX),
    ("cmd+alt+shift+a", pl::CMD_OPT_SHIFT_A_HEX),
    ("cmd+alt+shift+d", pl::CMD_OPT_SHIFT_D_HEX),
    ("cmd+alt+shift+w", pl::CMD_OPT_SHIFT_W_HEX),
    // Format Document (editor.action.formatDocument).
    ("cmd+alt+shift+f", pl::CMD_OPT_SHIFT_F_HEX),
    ("cmd+alt+arrow_left", pl::CMD_OPT_LEFT_HEX),
    ("cmd+alt+arrow_right", pl::CMD_OPT_RIGHT_HEX),
    // Multi-cursor: add cursor above / below.
    ("cmd+alt+arrow_up", pl::CMD_OPT_UP_HEX),
    ("cmd+alt+arrow_down", pl::CMD_OPT_DOWN_HEX),
    // Column (box) selection (#1560).
    ("cmd+alt+shift+arrow_up", pl::CMD_OPT_SHIFT_UP_HEX),
    ("cmd+alt+shift+arrow_down", pl::CMD_OPT_SHIFT_DOWN_HEX),
    ("cmd+alt+shift+arrow_left", pl::CMD_OPT_SHIFT_LEFT_HEX),
    ("cmd+alt+shift+arrow_right", pl::CMD_OPT_SHIFT_RIGHT_HEX),
    // Command Palette.
    ("cmd+shift+p", pl::CMD_SHIFT_P_HEX),
    ("cmd+f12", pl::CMD_F12_HEX),
    ("ctrl+shift+f12", pl::CTRL_SHIFT_F12_HEX),
];

/// Convert an iTerm2 Send-Hex payload (`"0x1b 0x5b 0x31 0x31 0x36 0x3b 0x39
/// 0x75"`) into a Ghostty `csi:` body (`"116;9u"`) by parsing the space
/// separated bytes and stripping the `ESC [` introducer. The remaining bytes
/// are always printable ASCII (digits, `;`, and a final byte such as `u`, `~`,
/// `D`, or `C`).
fn csi_body(hex: &str) -> String {
    let bytes: Vec<u8> = hex
        .split_whitespace()
        .filter_map(|token| u8::from_str_radix(token.trim_start_matches("0x"), 16).ok())
        .collect();
    let body = bytes.strip_prefix(&[0x1b, 0x5b]).unwrap_or(&bytes);
    body.iter().map(|&b| b as char).collect()
}

/// Render croft's managed keybind block: the begin marker, one `keybind` line
/// per forwarded chord (including the digit chords and any user keybindings),
/// and the end marker.
pub(crate) fn render_keybind_block() -> String {
    render_keybind_block_with(&crate::keymap::Keymap::load(
        &crate::keymap::keybindings_path(),
    ))
}

/// The block renderer, taking the user keymap explicitly so it can be tested
/// without touching the real config.
pub(crate) fn render_keybind_block_with(keymap: &crate::keymap::Keymap) -> String {
    let mut lines = Vec::with_capacity(CHORDS.len() + pl::CMD_DIGIT_CHORDS.len() + 2);
    lines.push(BLOCK_BEGIN.to_string());
    for (trigger, hex) in CHORDS {
        lines.push(format!(
            "{KEYBIND_PREFIX}{trigger}={CSI_ACTION}{}",
            csi_body(hex)
        ));
    }
    for (digit, (_key, hex)) in pl::CMD_DIGIT_CHORDS.iter().enumerate() {
        lines.push(format!(
            "{KEYBIND_PREFIX}cmd+{digit}={CSI_ACTION}{}",
            csi_body(hex)
        ));
    }
    // User keybindings: forward each reserved-Cmd chord via the same CSI-u
    // payload iTerm2 sends, so a rebind reaches croft under Ghostty too.
    for chord in keymap.chords() {
        if let (Some(trigger), Some((_key, hex))) =
            (chord.ghostty_trigger(), chord.iterm2_forwarder())
        {
            lines.push(format!(
                "{KEYBIND_PREFIX}{trigger}={CSI_ACTION}{}",
                csi_body(&hex)
            ));
        }
    }
    lines.push(BLOCK_END.to_string());
    lines.join("\n")
}

/// Drop any previously-installed croft block (between the markers, inclusive)
/// from existing config content, leaving every other line untouched. An
/// opening marker with no closing marker after it is no block: only that
/// marker line goes, and the user's lines after it stay (#1149).
fn strip_managed_block(content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let mut kept: Vec<&str> = Vec::new();
    let mut i = 0;
    while i < lines.len() {
        if lines[i].trim() == BLOCK_BEGIN {
            match lines[i + 1..].iter().position(|l| l.trim() == BLOCK_END) {
                Some(end) => i += end + 2,
                None => i += 1,
            }
            continue;
        }
        kept.push(lines[i]);
        i += 1;
    }
    kept.join("\n")
}

/// Merge croft's managed block into existing config content: strip any prior
/// croft block, then append the fresh block. Idempotent (running twice yields
/// the same result) and order-preserving for the user's own lines.
pub(crate) fn merge_config(existing: &str, block: &str) -> String {
    let user = strip_managed_block(existing);
    let user = user.trim_end_matches('\n');
    if user.is_empty() {
        format!("{block}\n")
    } else {
        format!("{user}\n\n{block}\n")
    }
}

/// Load → merge → save the Ghostty config, creating it (and its parent
/// directory) when absent.
pub fn install_keybinds(config_path: &Path) -> Result<()> {
    let existing = match std::fs::read_to_string(config_path) {
        Ok(content) => content,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => {
            return Err(e).with_context(|| format!("reading {}", config_path.display()));
        }
    };
    let merged = merge_config(&existing, &render_keybind_block());
    if let Some(parent) = config_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
    }
    std::fs::write(config_path, merged)
        .with_context(|| format!("writing {}", config_path.display()))?;
    Ok(())
}

/// Resolve the Ghostty config croft should edit, from `HOME` and
/// `XDG_CONFIG_HOME` (see [`config_path_in`]).
pub fn default_config_path() -> PathBuf {
    let home = std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_default();
    let xdg = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
    config_path_in(&home, xdg.as_deref(), cfg!(target_os = "macos"))
}

/// The Ghostty config to edit (#1439): the LAST that exists in the order
/// Ghostty loads them, `config` then `config.ghostty` in
/// `$XDG_CONFIG_HOME/ghostty` (a relative or empty `XDG_CONFIG_HOME` is
/// ignored, as the XDG spec says) and then, on macOS, in
/// `~/Library/Application Support/com.mitchellh.ghostty`. A later file's
/// keybind for the same trigger overrides an earlier one, so croft's
/// mappings only hold in the file loaded last. With
/// none, a new `config` (the name every Ghostty version reads) in the
/// application-support folder on macOS, else in the XDG folder. Checking
/// one fixed path and falling back to the macOS one wrote, on Linux, a file
/// Ghostty never reads.
pub(crate) fn config_path_in(home: &Path, xdg_config_home: Option<&Path>, macos: bool) -> PathBuf {
    let xdg = xdg_config_home
        .filter(|p| p.is_absolute())
        .map(Path::to_path_buf)
        .unwrap_or_else(|| home.join(".config"))
        .join(XDG_DIR);
    let mut dirs = vec![xdg.clone()];
    if macos {
        dirs.push(home.join(APP_SUPPORT_DIR));
    }
    dirs.iter()
        .flat_map(|dir| CONFIG_NAMES.iter().map(move |name| dir.join(name)))
        .rfind(|p| p.is_file())
        .unwrap_or_else(|| dirs.last().unwrap_or(&xdg).join("config"))
}

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

    /// #1439: the config is looked for where Ghostty reads it, under either
    /// file name and `XDG_CONFIG_HOME`.
    #[test]
    fn the_config_is_found_under_xdg_and_either_name() {
        let t = tempfile::tempdir().unwrap();
        let home = t.path();
        let put = |rel: &str| {
            let p = home.join(rel);
            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
            std::fs::write(&p, "font-size = 14\n").unwrap();
            p
        };
        let named = put(".config/ghostty/config.ghostty");
        for macos in [false, true] {
            assert_eq!(config_path_in(home, None, macos), named);
        }
        // `config.ghostty` loads after a legacy `config` beside it, so it wins.
        put(".config/ghostty/config");
        assert_eq!(config_path_in(home, None, false), named);
        // XDG_CONFIG_HOME moves the folder.
        let dots = put("dots/ghostty/config");
        assert_eq!(config_path_in(home, Some(&home.join("dots")), false), dots);
        // Application Support is loaded after the XDG folder on macOS, so
        // its file is the one whose keybinds win; Linux never reads it.
        let app = put("Library/Application Support/com.mitchellh.ghostty/config.ghostty");
        assert_eq!(config_path_in(home, None, true), app);
        assert_eq!(config_path_in(home, None, false), named);
        let legacy_app = put("Library/Application Support/com.mitchellh.ghostty/config");
        assert_eq!(
            config_path_in(home, None, true),
            app,
            "config.ghostty loads after the legacy name beside it"
        );
        std::fs::remove_file(&app).unwrap();
        assert_eq!(config_path_in(home, None, true), legacy_app);
        std::fs::remove_dir_all(home.join(".config")).unwrap();
        assert_eq!(config_path_in(home, None, true), legacy_app);
    }

    /// #1439: with no config yet, a new one goes where this OS's Ghostty
    /// reads it; a Linux setup never creates `~/Library`.
    #[test]
    fn a_missing_config_is_created_where_this_os_reads_it() {
        let t = tempfile::tempdir().unwrap();
        let home = t.path();
        assert_eq!(
            config_path_in(home, None, false),
            home.join(".config/ghostty/config")
        );
        assert_eq!(
            config_path_in(home, Some(&home.join("dots")), false),
            home.join("dots/ghostty/config")
        );
        assert_eq!(
            config_path_in(home, None, true),
            home.join("Library/Application Support/com.mitchellh.ghostty/config")
        );
        // A relative XDG_CONFIG_HOME is not a base directory.
        assert_eq!(
            config_path_in(home, Some(Path::new("rel")), false),
            home.join(".config/ghostty/config")
        );
        assert!(!home.join("Library").exists());
    }

    #[test]
    fn user_keybinding_appends_a_forwarding_keybind_line() {
        let km = crate::keymap::Keymap::from_json(
            r#"[{ "key": "cmd+j", "command": "toggle_terminal" }]"#,
        );
        let block = render_keybind_block_with(&km);
        // cmd+j forwards as CSI 106;9u (106 = 'j', modbyte 9 = Cmd).
        assert!(
            block.contains("keybind = cmd+j=csi:106;9u"),
            "the user's cmd+j binding must appear as a Ghostty csi forwarder:\n{block}"
        );
    }

    #[test]
    fn csi_body_strips_the_esc_bracket_introducer() {
        assert_eq!(csi_body(pl::CMD_T_HEX), "116;9u");
        assert_eq!(csi_body(pl::CMD_OPT_LEFT_HEX), "1;11D");
        assert_eq!(csi_body(pl::CMD_OPT_RIGHT_HEX), "1;11C");
        assert_eq!(csi_body(pl::CMD_F12_HEX), "24;9~");
    }

    /// #1560: Cmd+Shift+Opt+arrows forward as the arrow with
    /// Shift | Alt | Super, for column selection.
    #[test]
    fn rendered_block_forwards_cmd_shift_opt_arrows() {
        let block = render_keybind_block();
        for (key, end) in [("up", 'A'), ("down", 'B'), ("left", 'D'), ("right", 'C')] {
            let line = format!("keybind = cmd+alt+shift+arrow_{key}=csi:1;12{end}");
            assert!(block.contains(&line), "{line} missing:\n{block}");
        }
    }

    #[test]
    fn every_chord_body_is_printable_ascii_and_nonempty() {
        for (trigger, hex) in CHORDS {
            let body = csi_body(hex);
            assert!(!body.is_empty(), "empty body for {trigger}");
            assert!(
                body.chars().all(|c| c.is_ascii() && !c.is_control()),
                "non-printable body {body:?} for {trigger}"
            );
        }
    }

    #[test]
    fn rendered_block_contains_cmd_t_and_a_digit_chord() {
        let block = render_keybind_block();
        assert!(block.starts_with(BLOCK_BEGIN));
        assert!(block.ends_with(BLOCK_END));
        assert!(block.contains("keybind = cmd+t=csi:116;9u"));
        // cmd+5 forwards codepoint '5' (53) with Super.
        assert!(block.contains("keybind = cmd+5=csi:53;9u"));
        // The backslash trigger survives literally.
        assert!(block.contains("keybind = cmd+\\=csi:92;9u"));
        // Go to Bracket: same '\' key with Shift (modifier byte 10).
        assert!(block.contains("keybind = cmd+shift+\\=csi:92;10u"));
    }

    #[test]
    fn merge_into_empty_config_is_just_the_block() {
        let merged = merge_config("", &render_keybind_block());
        assert_eq!(merged, format!("{}\n", render_keybind_block()));
    }

    #[test]
    fn merge_preserves_user_lines_and_appends_block() {
        let existing = "font-size = 14\ntheme = dark\n";
        let merged = merge_config(existing, &render_keybind_block());
        assert!(merged.starts_with("font-size = 14\ntheme = dark\n"));
        assert!(merged.contains(BLOCK_BEGIN));
        assert!(merged.contains("keybind = cmd+t=csi:116;9u"));
    }

    #[test]
    fn merge_is_idempotent() {
        let block = render_keybind_block();
        let once = merge_config("font-size = 14\n", &block);
        let twice = merge_config(&once, &block);
        assert_eq!(once, twice);
        // Exactly one managed block survives.
        assert_eq!(twice.matches(BLOCK_BEGIN).count(), 1);
    }

    /// #1149: an opening marker with no closing one is no block; the lines
    /// after it are the user's and stay.
    #[test]
    fn an_opening_marker_without_a_closing_one_keeps_the_lines_after_it() {
        let block = render_keybind_block();
        let existing =
            format!("font-size = 13\n{BLOCK_BEGIN}\ntheme = dracula\nwindow-padding-x = 8\n");
        let merged = merge_config(&existing, &block);
        assert_eq!(
            merged,
            format!("font-size = 13\ntheme = dracula\nwindow-padding-x = 8\n\n{block}\n")
        );
        assert_eq!(
            merged.matches(BLOCK_BEGIN).count(),
            1,
            "the stray marker goes"
        );
    }

    /// A complete old block between user lines is still replaced, and the
    /// lines after it kept.
    #[test]
    fn a_complete_block_is_still_replaced_and_lines_after_it_kept() {
        let block = render_keybind_block();
        let existing = format!(
            "font-size = 13\n{BLOCK_BEGIN}\nkeybind = cmd+x=csi:1u\n{BLOCK_END}\ntheme = dracula\nwindow-padding-x = 8\n"
        );
        let merged = merge_config(&existing, &block);
        assert_eq!(
            merged,
            format!("font-size = 13\ntheme = dracula\nwindow-padding-x = 8\n\n{block}\n")
        );
        assert!(!merged.contains("cmd+x=csi:1u"), "the old block's lines go");
    }

    #[test]
    fn install_keeps_settings_after_a_stray_opening_marker() {
        let dir = tempfile::tempdir().unwrap();
        let cfg = dir.path().join("config");
        std::fs::write(
            &cfg,
            format!("font-size = 13\n{BLOCK_BEGIN}\ntheme = dracula\nwindow-padding-x = 8\n"),
        )
        .unwrap();
        install_keybinds(&cfg).unwrap();
        let content = std::fs::read_to_string(&cfg).unwrap();
        assert!(
            content.contains("theme = dracula\nwindow-padding-x = 8\n"),
            "{content}"
        );
        assert_eq!(content.matches(BLOCK_BEGIN).count(), 1);
    }

    #[test]
    fn install_round_trips_through_disk_and_replaces_old_block() {
        let dir = tempfile::tempdir().unwrap();
        let cfg = dir.path().join("config");
        std::fs::write(&cfg, "font-size = 13\n").unwrap();
        install_keybinds(&cfg).unwrap();
        install_keybinds(&cfg).unwrap();
        let content = std::fs::read_to_string(&cfg).unwrap();
        assert_eq!(content.matches(BLOCK_BEGIN).count(), 1);
        assert!(content.starts_with("font-size = 13\n"));
        assert!(content.contains("keybind = cmd+t=csi:116;9u"));
    }

    #[test]
    fn install_creates_missing_config_and_parent_dir() {
        let dir = tempfile::tempdir().unwrap();
        let cfg = dir.path().join("nested/ghostty/config");
        install_keybinds(&cfg).unwrap();
        let content = std::fs::read_to_string(&cfg).unwrap();
        assert!(content.contains("keybind = cmd+t=csi:116;9u"));
    }
}