croft-software 0.2.232

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
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
//! Settings editor model (#612): every setting croft has, its effective
//! value, which layer set it, and how it is edited in place.
//!
//! The rows come from the merged view [`crate::config_layers`] builds, so a
//! workspace override shows as the value in force with its layer named.
//! Writing goes to one layer file at a time with [`set_key`]; the caller
//! re-merges afterwards.

use crate::config_layers::LayerKind;
use crate::settings_table::Values;
use serde_json::Value;
use std::collections::BTreeMap;

/// How a setting is edited in place.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Kind {
    /// Enter flips it.
    Bool,
    /// Enter steps through these values.
    Choice(Vec<String>),
    /// Enter asks for a number.
    Number,
    /// Enter asks for text.
    Text,
    /// Objects and arrays: edited in the JSON file.
    Json,
}

/// One setting as the editor lists it.
#[derive(Debug, Clone, PartialEq)]
pub struct Row {
    pub key: String,
    pub value: Value,
    pub kind: Kind,
    pub layer: LayerKind,
    /// The value differs from croft's built-in default (#1655), whichever
    /// layer set it: what "what have I changed?" lists.
    pub modified: bool,
}

/// The string settings whose values come from a fixed set
/// ([`crate::settings_table::Values`]). An empty (default) value counts as
/// the first choice, so Enter moves it to the second. An optional setting's
/// first choice is the empty one, its default, which Enter writes as no
/// value at all (#1555).
pub fn choices(key: &str) -> Option<Vec<String>> {
    let fixed = match crate::settings_table::values(key) {
        Values::OneOf(fixed) | Values::OptionalOneOf(fixed) => fixed,
        Values::Language => {
            let langs = crate::i18n::languages(&crate::paths::config_dir());
            return Some(std::iter::once(String::new()).chain(langs).collect());
        }
        Values::Theme => {
            return Some(
                crate::theme::Theme::all()
                    .iter()
                    .map(|t| t.id().to_string())
                    .collect(),
            );
        }
        Values::Any | Values::OptionalText | Values::OptionalNumber => return None,
    };
    Some(fixed.iter().map(|c| c.to_string()).collect())
}

/// The optional settings (#1555): unset, their value is `null`. Text and
/// Number rows of these take an empty entry as unset.
fn is_optional(key: &str) -> bool {
    crate::settings_table::values(key).optional()
}

/// How an unset (`null`) setting is edited: its declared kind, since `null`
/// says nothing of its type, or, for a setting with no declaration, the JSON
/// file.
fn unset_kind(key: &str) -> Kind {
    match crate::settings_table::values(key) {
        Values::OptionalText => Kind::Text,
        Values::OptionalNumber => Kind::Number,
        _ => choices(key).map_or(Kind::Json, Kind::Choice),
    }
}

/// Every top-level setting of `prefs` in key order, with the layer
/// `provenance` says set it.
pub fn rows(prefs: &crate::prefs::Prefs, provenance: &BTreeMap<String, LayerKind>) -> Vec<Row> {
    let Ok(Value::Object(map)) = serde_json::to_value(prefs) else {
        return Vec::new();
    };
    let defaults = match serde_json::to_value(crate::prefs::Prefs::default()) {
        Ok(Value::Object(d)) => d,
        _ => serde_json::Map::new(),
    };
    let mut out: Vec<Row> = map
        .into_iter()
        .map(|(key, value)| {
            let kind = match &value {
                Value::Bool(_) => Kind::Bool,
                Value::Number(_) => Kind::Number,
                Value::String(_) => choices(&key).map(Kind::Choice).unwrap_or(Kind::Text),
                Value::Null => unset_kind(&key),
                _ => Kind::Json,
            };
            let layer = crate::config_layers::layer_of(provenance, &key);
            let modified = defaults.get(&key) != Some(&value);
            Row {
                key,
                value,
                kind,
                layer,
                modified,
            }
        })
        .collect();
    out.sort_by(|a, b| a.key.cmp(&b.key));
    out
}

/// What a row shows for a setting at its default: an empty string, or an
/// optional setting that is unset.
pub const DEFAULT_LABEL: &str = "(default)";

/// A value as one line: strings bare, `(default)` for an empty one or an
/// unset optional one, objects and arrays as compact JSON.
pub fn display(value: &Value) -> String {
    match value {
        Value::String(s) if s.is_empty() => String::from(DEFAULT_LABEL),
        Value::Null => String::from(DEFAULT_LABEL),
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// Whether `row` matches every word of `query` in its key (underscores read
/// as spaces) or its displayed value, ignoring case.
pub fn matches(row: &Row, query: &str) -> bool {
    let hay = format!(
        "{} {} {}",
        row.key,
        row.key.replace('_', " "),
        display(&row.value)
    )
    .to_lowercase();
    query
        .split_whitespace()
        .all(|w| hay.contains(&w.to_lowercase()))
}

/// The value Enter moves a Bool or Choice row to; `None` for other kinds.
pub fn next_value(row: &Row) -> Option<Value> {
    match (&row.kind, &row.value) {
        (Kind::Bool, Value::Bool(b)) => Some(Value::Bool(!b)),
        (Kind::Choice(c), v) if !c.is_empty() => {
            let now = v.as_str().unwrap_or_default();
            let at = c.iter().position(|x| x == now).unwrap_or(0);
            let next = &c[(at + 1) % c.len()];
            Some(if next.is_empty() && is_optional(&row.key) {
                Value::Null
            } else {
                Value::String(next.clone())
            })
        }
        _ => None,
    }
}

/// The value typed into a Number or Text row's prompt (#1555). A Number
/// must be a whole number. An optional setting left empty, or given back
/// `(default)`, is unset, except `review_ai_prefix`, whose empty value is
/// itself a setting (no marker); any other text setting's `(default)` is
/// its empty default.
pub fn typed_value(row: &Row, text: &str) -> Result<Value, String> {
    let t = text.trim();
    let optional = is_optional(&row.key);
    if t == DEFAULT_LABEL {
        return Ok(if optional {
            Value::Null
        } else {
            Value::from("")
        });
    }
    match row.kind {
        Kind::Number if t.is_empty() && optional => Ok(Value::Null),
        Kind::Number => t
            .parse::<u64>()
            .map(Value::from)
            .map_err(|_| format!("{} needs a whole number, not \"{t}\"", row.key)),
        _ if t.is_empty() && optional && row.key != "review_ai_prefix" => Ok(Value::Null),
        _ => Ok(Value::from(t)),
    }
}

/// Whether `key` may be set to `value` (#1555): the settings, with it set,
/// still read back as croft's settings. A value of the wrong type, or a
/// word an enum setting doesn't know, would otherwise be saved, reported as
/// saved, and then ignored.
pub fn check(prefs: &crate::prefs::Prefs, key: &str, value: &Value) -> Result<(), String> {
    let Ok(Value::Object(mut map)) = serde_json::to_value(prefs) else {
        return Ok(());
    };
    map.insert(key.to_string(), value.clone());
    serde_json::from_value::<crate::prefs::Prefs>(Value::Object(map))
        .map(|_| ())
        .map_err(|_| format!("{key} can't be {}", display(value)))
}

/// The 0-based line of top-level `key` in a layer file's `text`, for
/// opening a JSON-only setting where it is written (#1555).
pub fn key_line(text: &str, key: &str) -> Option<usize> {
    let quoted = format!("\"{key}\"");
    text.lines().position(|l| {
        l.trim_start()
            .strip_prefix(&quoted)
            .is_some_and(|rest| rest.trim_start().starts_with(':'))
    })
}

/// `text` (a layer file's JSONC object, or empty) with `key` set to
/// `value`; every other key keeps its value and its place, and a new key
/// goes last. A `null` value takes the key out instead, so the setting
/// falls back to its default (#1555). Read as JSONC like the layer loader,
/// and edited in place, so the file's comments and layout survive
/// ([`written`], #2904). An error when the text is not a JSON object.
pub fn set_key(text: &str, key: &str, value: Value) -> Result<String, String> {
    let mut map = if text.trim().is_empty() {
        serde_json::Map::new()
    } else {
        parse_layer(text)?
    };
    if value.is_null() {
        map.remove(key);
    } else {
        map.insert(key.to_string(), value);
    }
    written(text, map)
}

/// A layer file's text as its JSON object, read as JSONC like the layer
/// loader: comments and trailing commas are allowed, as in VS Code's
/// `settings.json` and in the file Open Settings (JSON) creates.
fn parse_layer(text: &str) -> Result<serde_json::Map<String, Value>, String> {
    match serde_json::from_str::<Value>(&crate::jsonc::strip_jsonc(text)) {
        Ok(Value::Object(m)) => Ok(m),
        Ok(_) => Err(String::from("the settings file is not a JSON object")),
        Err(e) => Err(format!("the settings file does not parse: {e}")),
    }
}

/// What a layer file `text` becomes holding `map`: the file edited in place,
/// so its comments, layout and key order stay as the user wrote them, as
/// when croft saves a setting from anywhere else (#1129, #2904). Plain,
/// pretty-printed JSON only for a file there was none of, or one the
/// in-place edit cannot place.
fn written(text: &str, map: serde_json::Map<String, Value>) -> Result<String, String> {
    let new = Value::Object(map);
    if !text.trim().is_empty()
        && let Some(edited) = crate::jsonc_edit::update(text, &new)
    {
        return Ok(edited);
    }
    serde_json::to_string_pretty(&new)
        .map(|s| s + "\n")
        .map_err(|e| e.to_string())
}

/// `text` (a layer file's JSONC object) without `key` (#1655), written
/// like [`set_key`], in place; `Ok(None)` when the file does not set it,
/// so nothing is written. Also drops `key` from the active `platform`
/// scope block (`"linux"` / `"macos"` / `"android"`), which the loader
/// merges over the flat keys. An error when the text is not a JSON object.
pub fn remove_key(text: &str, key: &str, platform: &str) -> Result<Option<String>, String> {
    if text.trim().is_empty() {
        return Ok(None);
    }
    let mut map = parse_layer(text)?;
    let mut removed = map.remove(key).is_some();
    if let Some(Value::Object(block)) = map.get_mut(platform) {
        removed |= block.remove(key).is_some();
    }
    if !removed {
        return Ok(None);
    }
    written(text, map).map(Some)
}

/// `text` (a layer file's JSONC object) with `item` taken out of the list
/// at `key`, at the top level and in every platform scope block, each of
/// which the loader merges over the flat keys on its platform; edited in
/// place like [`set_key`]. `Ok(None)` when no list there holds `item`, so
/// nothing is written. An error when the text is not a JSON object.
pub fn remove_from_list(text: &str, key: &str, item: &str) -> Result<Option<String>, String> {
    if text.trim().is_empty() {
        return Ok(None);
    }
    let mut map = parse_layer(text)?;
    let mut removed = drop_list_item(&mut map, key, item);
    for platform in crate::config_layers::PLATFORM_KEYS {
        if let Some(Value::Object(block)) = map.get_mut(*platform) {
            removed |= drop_list_item(block, key, item);
        }
    }
    if !removed {
        return Ok(None);
    }
    written(text, map).map(Some)
}

/// Take `item` out of the list at `key` in `map`; whether it was there.
fn drop_list_item(map: &mut serde_json::Map<String, Value>, key: &str, item: &str) -> bool {
    let Some(Value::Array(list)) = map.get_mut(key) else {
        return false;
    };
    let before = list.len();
    list.retain(|v| v.as_str() != Some(item));
    list.len() != before
}

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

    #[test]
    fn rows_cover_every_setting_with_its_kind_and_layer() {
        let prefs = crate::prefs::Prefs {
            auto_save: true,
            problems_scope: String::from("open_files"),
            ..Default::default()
        };
        let provenance = BTreeMap::from([(String::from("auto_save"), LayerKind::Workspace)]);
        let all = rows(&prefs, &provenance);
        let expected = serde_json::to_value(&prefs)
            .unwrap()
            .as_object()
            .unwrap()
            .len();
        assert_eq!(all.len(), expected, "one row per setting");
        let keys: Vec<&str> = all.iter().map(|r| r.key.as_str()).collect();
        let mut sorted = keys.clone();
        sorted.sort();
        assert_eq!(keys, sorted, "in key order");
        let get = |k: &str| all.iter().find(|r| r.key == k).unwrap();
        assert_eq!(get("auto_save").kind, Kind::Bool);
        assert_eq!(get("auto_save").value, json!(true));
        assert_eq!(get("auto_save").layer, LayerKind::Workspace);
        assert_eq!(get("copy_on_select").layer, LayerKind::Default);
        assert_eq!(
            get("problems_scope").kind,
            Kind::Choice(vec!["whole_project".into(), "open_files".into()])
        );
        assert!(matches!(get("theme").kind, Kind::Choice(ref c) if c.len() > 1));
        assert_eq!(get("explorer_views").kind, Kind::Json);
    }

    /// #2920 review: an item comes out of the list wherever a layer file
    /// sets it, the top level and each platform block, and the file keeps
    /// its comments and other keys; a file that does not list it is left
    /// alone.
    #[test]
    fn an_item_comes_out_of_a_list_at_the_top_and_in_every_platform_block() {
        let text = "{\n  // mine\n  \"theme\": \"nord\",\n  \"mcp_consented\": [\"a\", \"b\"],\n  \"linux\": { \"mcp_consented\": [\"a\"] },\n  \"macos\": { \"mcp_consented\": [\"c\", \"a\"] }\n}\n";
        let edited = remove_from_list(text, "mcp_consented", "a")
            .unwrap()
            .expect("the file lists it");
        let v: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(&edited)).unwrap();
        assert_eq!(v["mcp_consented"], json!(["b"]));
        assert_eq!(v["linux"]["mcp_consented"], json!([]));
        assert_eq!(v["macos"]["mcp_consented"], json!(["c"]));
        assert!(
            edited.contains("// mine") && edited.contains("nord"),
            "{edited}"
        );
        assert_eq!(remove_from_list(&edited, "mcp_consented", "a"), Ok(None));
        assert_eq!(remove_from_list("", "mcp_consented", "a"), Ok(None));
    }

    #[test]
    fn values_display_on_one_line() {
        assert_eq!(display(&json!("open_files")), "open_files");
        assert_eq!(display(&json!("")), "(default)");
        assert_eq!(display(&json!(true)), "true");
        assert_eq!(display(&json!(12)), "12");
        assert_eq!(display(&json!({"a": 1})), "{\"a\":1}");
        assert_eq!(display(&Value::Null), "(default)", "#1555: not `null`");
    }

    /// #1555: an unset optional setting is edited as what it is, not sent
    /// to the JSON file because its value, `null`, says nothing of its type.
    #[test]
    fn unset_optional_settings_get_their_real_kind() {
        let all = rows(&crate::prefs::Prefs::default(), &BTreeMap::new());
        let get = |k: &str| all.iter().find(|r| r.key == k).unwrap().kind.clone();
        let Kind::Choice(langs) = get("locale") else {
            panic!("locale is a choice: {:?}", get("locale"));
        };
        assert_eq!(langs[0], "", "the first choice is the system's language");
        for lang in ["en", "de", "es"] {
            assert!(langs.iter().any(|l| l == lang), "{lang} in {langs:?}");
        }
        assert_eq!(get("terminal_rewind_mb"), Kind::Number);
        for key in [
            "codeql_cli_path",
            "lane_agent",
            "review_ai_prefix",
            "screen_reader_command",
        ] {
            assert_eq!(get(key), Kind::Text, "{key}");
        }
        assert_eq!(
            get("code_scanning"),
            Kind::Choice(vec!["off".into(), "on".into(), "prompt".into()])
        );
    }

    /// #2908: the two optional settings added after #1555 get their kinds
    /// too. They were edited as raw JSON, so a formatter id needed its
    /// quotes and `color_depth` offered no list of its values.
    #[test]
    fn default_formatter_and_color_depth_unset_get_their_real_kind() {
        let all = rows(&crate::prefs::Prefs::default(), &BTreeMap::new());
        let get = |k: &str| all.iter().find(|r| r.key == k).unwrap().kind.clone();
        assert_eq!(get("default_formatter"), Kind::Text);
        let Kind::Choice(depths) = get("color_depth") else {
            panic!("color_depth is a choice: {:?}", get("color_depth"));
        };
        assert_eq!(depths[0], "", "the first choice is the terminal's own");
        for depth in &depths[1..] {
            assert!(
                crate::color_depth::ColorDepth::from_setting(depth).is_some(),
                "{depth} is a depth croft reads"
            );
        }
        // Stepping past the last depth goes back to unset, not to "".
        let last = Row {
            key: "color_depth".into(),
            value: json!("16"),
            kind: get("color_depth"),
            layer: LayerKind::Default,
            modified: true,
        };
        assert_eq!(next_value(&last), Some(Value::Null));
    }

    /// #2908: every setting that is unset by default has a declared kind, so
    /// the next optional setting added cannot fall back to the JSON file
    /// unnoticed, as these two did.
    #[test]
    fn every_unset_setting_has_a_declared_kind() {
        for row in rows(&crate::prefs::Prefs::default(), &BTreeMap::new()) {
            if row.value.is_null() {
                assert_ne!(row.kind, Kind::Json, "{} has no declared kind", row.key);
            }
        }
    }

    /// #1555 negative: objects and lists are still edited in the JSON file.
    #[test]
    fn objects_and_lists_stay_json_rows() {
        let all = rows(&crate::prefs::Prefs::default(), &BTreeMap::new());
        let get = |k: &str| all.iter().find(|r| r.key == k).unwrap().kind.clone();
        assert_eq!(get("files_exclude"), Kind::Json);
        assert_eq!(get("explorer_views"), Kind::Json);
    }

    /// #1555: stepping an optional choice past its last value unsets it.
    #[test]
    fn an_optional_choice_steps_back_to_unset() {
        let langs = Kind::Choice(vec!["".into(), "de".into(), "es".into()]);
        let locale = |v: Value| row("locale", v, langs.clone());
        assert_eq!(next_value(&locale(Value::Null)), Some(json!("de")));
        assert_eq!(next_value(&locale(json!("es"))), Some(Value::Null));
    }

    /// #1555: a typed value is a number for a number row, and an optional
    /// setting left empty, or given `(default)`, is unset.
    #[test]
    fn a_typed_value_parses_or_unsets_an_optional_setting() {
        let rewind = row("terminal_rewind_mb", Value::Null, Kind::Number);
        assert_eq!(typed_value(&rewind, " 500 "), Ok(json!(500)));
        assert_eq!(typed_value(&rewind, ""), Ok(Value::Null));
        assert_eq!(typed_value(&rewind, "(default)"), Ok(Value::Null));
        assert!(typed_value(&rewind, "lots").unwrap_err().contains("number"));
        let codeql = row("codeql_cli_path", Value::Null, Kind::Text);
        assert_eq!(
            typed_value(&codeql, "/opt/codeql"),
            Ok(json!("/opt/codeql"))
        );
        assert_eq!(typed_value(&codeql, "  "), Ok(Value::Null));
    }

    /// #1555 negative: a required number still needs one, an empty AI
    /// review prefix is its own setting (no marker), and a plain text
    /// setting's `(default)` is its empty default, not unset.
    #[test]
    fn empty_entries_unset_only_what_may_be_unset() {
        let scrollback = row("terminal_scrollback", json!(1000), Kind::Number);
        assert!(typed_value(&scrollback, "").is_err());
        let prefix = row("review_ai_prefix", Value::Null, Kind::Text);
        assert_eq!(typed_value(&prefix, ""), Ok(json!("")));
        assert_eq!(typed_value(&prefix, "(default)"), Ok(Value::Null));
        let font = row("a_text_setting", json!(""), Kind::Text);
        assert_eq!(typed_value(&font, "(default)"), Ok(json!("")));
    }

    /// #1555: a value the setting can't hold is refused; one it can, and
    /// unsetting an optional setting, are not.
    #[test]
    fn check_refuses_a_value_the_setting_cannot_hold() {
        let prefs = crate::prefs::Prefs::default();
        assert!(check(&prefs, "code_scanning", &json!("enabled")).is_err());
        assert!(check(&prefs, "auto_save", &json!("yes")).is_err());
        assert_eq!(check(&prefs, "code_scanning", &json!("prompt")), Ok(()));
        assert_eq!(check(&prefs, "terminal_rewind_mb", &json!(500)), Ok(()));
        assert_eq!(check(&prefs, "locale", &Value::Null), Ok(()));
    }

    /// #1555: a `null` value takes the key out of the layer file.
    #[test]
    fn set_key_with_null_removes_the_key() {
        let out = set_key(
            "{\"locale\": \"de\", \"auto_save\": true}",
            "locale",
            Value::Null,
        )
        .unwrap();
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v, json!({"auto_save": true}));
    }

    #[test]
    fn key_line_finds_a_top_level_key() {
        let text = "{\n  \"files\": 1,\n  \"files_exclude\" : [],\n  \"x\": \"files_exclude\"\n}";
        assert_eq!(key_line(text, "files_exclude"), Some(2));
        assert_eq!(key_line(text, "files"), Some(1));
        assert_eq!(key_line(text, "search_exclude"), None);
    }

    fn row(key: &str, value: Value, kind: Kind) -> Row {
        Row {
            key: key.into(),
            value,
            kind,
            layer: LayerKind::Default,
            modified: false,
        }
    }

    #[test]
    fn search_reads_underscores_as_spaces_and_matches_values() {
        let r = row("format_on_save", json!(true), Kind::Bool);
        assert!(matches(&r, "format save"));
        assert!(matches(&r, "FORMAT_ON"));
        assert!(matches(&r, "true"));
        assert!(!matches(&r, "format type"));
    }

    #[test]
    fn enter_flips_a_bool_and_steps_a_choice_wrapping_round() {
        assert_eq!(
            next_value(&row("a", json!(false), Kind::Bool)),
            Some(json!(true))
        );
        let c = Kind::Choice(vec!["auto".into(), "on".into(), "off".into()]);
        assert_eq!(
            next_value(&row("p", json!("on"), c.clone())),
            Some(json!("off"))
        );
        assert_eq!(
            next_value(&row("p", json!("off"), c.clone())),
            Some(json!("auto"))
        );
        // An empty or unknown value is the first choice, so Enter moves on.
        assert_eq!(next_value(&row("p", json!(""), c)), Some(json!("on")));
        assert_eq!(next_value(&row("n", json!(3), Kind::Number)), None);
    }

    #[test]
    fn set_key_writes_one_key_and_keeps_the_rest() {
        let out = set_key(
            "{\n  \"theme\": \"dark\",\n  \"auto_save\": false\n}",
            "auto_save",
            json!(true),
        )
        .unwrap();
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v, json!({"theme": "dark", "auto_save": true}));
        assert_eq!(
            serde_json::from_str::<Value>(&set_key("", "k", json!(1)).unwrap()).unwrap(),
            json!({"k": 1})
        );
        assert!(set_key("[1, 2]", "k", json!(1)).is_err());
        assert!(set_key("{ broken", "k", json!(1)).is_err());
    }

    /// #2904: a layer file is JSONC, like VS Code's `settings.json` and the
    /// file Open Settings (JSON) creates. A change is written in place, so
    /// its comments, trailing comma and layout survive; the strict parse
    /// refused the file and a pretty-print would have dropped them.
    #[test]
    fn set_key_edits_a_commented_file_in_place() {
        let text =
            "{\n  // mine\n  \"theme\": \"dark\", // the colours\n  \"auto_save\": false,\n}\n";
        let out = set_key(text, "auto_save", json!(true)).unwrap();
        assert!(
            out.contains("// mine") && out.contains("// the colours"),
            "{out}"
        );
        let v: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(&out)).unwrap();
        assert_eq!(v, json!({"theme": "dark", "auto_save": true}));

        let added = set_key(text, "format_on_save", json!(true)).unwrap();
        assert!(added.contains("// mine"), "{added}");
        let v: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(&added)).unwrap();
        assert_eq!(v["format_on_save"], json!(true));
        assert_eq!(v["theme"], json!("dark"));

        let cleared = remove_key(text, "theme", "linux").unwrap().unwrap();
        assert!(cleared.contains("// mine"), "{cleared}");
        let v: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(&cleared)).unwrap();
        assert_eq!(v, json!({"auto_save": false}));
    }

    #[test]
    fn remove_key_reads_jsonc_and_clears_the_active_platform_block() {
        let jsonc = "{\n  // mine\n  \"theme\": \"dark\",\n  \"auto_save\": true,\n}";
        let out = remove_key(jsonc, "auto_save", "linux").unwrap().unwrap();
        // Edited in place, the comment stays (#2904).
        assert!(out.contains("// mine"), "{out}");
        let v: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(&out)).unwrap();
        assert_eq!(v, json!({"theme": "dark"}));

        let scoped = r#"{"theme":"dark","linux":{"theme":"nord"},"macos":{"theme":"x"}}"#;
        let out = remove_key(scoped, "theme", "linux").unwrap().unwrap();
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v, json!({"linux": {}, "macos": {"theme": "x"}}));

        let only_scoped = r#"{"linux":{"auto_save":true}}"#;
        let out = remove_key(only_scoped, "auto_save", "linux")
            .unwrap()
            .unwrap();
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v, json!({"linux": {}}));

        assert_eq!(remove_key(only_scoped, "auto_save", "macos").unwrap(), None);
        assert_eq!(remove_key("", "k", "linux").unwrap(), None);
        assert!(remove_key("[1, 2]", "k", "linux").is_err());
        assert!(remove_key("{ broken", "k", "linux").is_err());
    }
}