Skip to main content

nu_protocol/config/
mod.rs

1//! Module containing the internal representation of user configuration
2
3use crate::FromValue;
4use crate::{self as nu_protocol, Filesize};
5use helper::*;
6use prelude::*;
7use std::collections::HashMap;
8
9pub use ansi_coloring::UseAnsiColoring;
10pub use clip::ClipConfig;
11pub use completions::{
12    CompletionAlgorithm, CompletionConfig, CompletionSort, ExternalCompleterConfig,
13};
14pub use datetime_format::DatetimeFormatConfig;
15pub use defaults::default_color_config;
16pub use display_errors::DisplayErrors;
17pub use duration_max_unit::DurationMaxUnit;
18pub use filesize::FilesizeConfig;
19pub use helper::extract_value;
20pub use hinter::HinterConfig;
21pub use history::{HistoryConfig, HistoryFileFormat, HistoryPath};
22pub use hooks::Hooks;
23pub use key_spec::{
24    EditModeName, KeyCodeSpec, KeyModifier, MenuInputMode, MenuLayout, MenuOutputMode,
25    VALID_KEYBINDING_MODES,
26};
27pub use ls::LsConfig;
28pub use output::{BannerKind, ErrorStyle};
29pub use plugin_gc::{PluginGcConfig, PluginGcConfigs};
30pub use reedline::{CursorShapeConfig, EditBindings, NuCursorShape, ParsedKeybinding, ParsedMenu};
31pub use rm::RmConfig;
32pub use shell_integration::ShellIntegrationConfig;
33pub use status_line::StatusLineConfig;
34pub use table::{FooterMode, TableConfig, TableIndent, TableIndexMode, TableMode, TrimStrategy};
35
36mod ansi_coloring;
37mod clip;
38mod completions;
39mod datetime_format;
40mod defaults;
41mod display_errors;
42mod duration_max_unit;
43mod error;
44mod filesize;
45mod helper;
46mod hinter;
47mod history;
48mod hooks;
49mod key_spec;
50mod ls;
51mod output;
52mod plugin_gc;
53mod prelude;
54mod reedline;
55mod rm;
56mod shell_integration;
57mod status_line;
58mod table;
59
60#[derive(Clone, Debug, IntoValue, Serialize, Deserialize)]
61pub struct Config {
62    pub filesize: FilesizeConfig,
63    pub table: TableConfig,
64    pub ls: LsConfig,
65    pub clip: ClipConfig,
66    pub color_config: HashMap<String, Value>,
67    pub footer_mode: FooterMode,
68    pub float_precision: i64,
69    pub recursion_limit: i64,
70    pub use_ansi_coloring: UseAnsiColoring,
71    pub completions: CompletionConfig,
72    pub edit_mode: EditBindings,
73    pub show_hints: bool,
74    pub hinter: HinterConfig,
75    pub status_line: StatusLineConfig,
76    pub history: HistoryConfig,
77    pub keybindings: Vec<ParsedKeybinding>,
78    pub abbreviations: HashMap<String, String>,
79    pub menus: Vec<ParsedMenu>,
80    pub hooks: Hooks,
81    pub rm: RmConfig,
82    pub shell_integration: ShellIntegrationConfig,
83    pub buffer_editor: Value,
84    pub show_banner: BannerKind,
85    pub bracketed_paste: bool,
86    pub render_right_prompt_on_last_line: bool,
87    pub explore: HashMap<String, Value>,
88    /// Styles for the `tui` command family (`$env.config.tui`).
89    pub tui: HashMap<String, Value>,
90    pub cursor_shape: CursorShapeConfig,
91    pub datetime_format: DatetimeFormatConfig,
92    pub error_style: ErrorStyle,
93    pub error_lines: i64,
94    pub display_errors: DisplayErrors,
95    pub use_kitty_protocol: bool,
96    pub highlight_resolved_externals: bool,
97    pub auto_cd_implicit: bool,
98    pub duration_max_unit: DurationMaxUnit,
99    /// Maximum estimated memory size of the interactive last-result payload (`$ans.last`).
100    ///
101    /// Measured with [`Value::memory_size`]. Default is `0` (no `.last` payload; opt-in).
102    /// Oversized results are truncated to fit this budget. The variable name itself is a code
103    /// constant (`LAST_RESULT_VAR_NAME`), not a config option. With a positive budget, `$ans`
104    /// is `{ last, exit_code, duration, command }`. With `0`, `$ans` still has `exit_code`,
105    /// `duration`, and `command` but omits `last` entirely.
106    pub max_last_result_size: Filesize,
107    /// Configuration for plugins.
108    ///
109    /// Users can provide configuration for a plugin through this entry.  The entry name must
110    /// match the registered plugin name so `plugin add nu_plugin_example` will be able to place
111    /// its configuration under a `nu_plugin_example` column.
112    pub plugins: HashMap<String, Value>,
113    /// Configuration for plugin garbage collection.
114    pub plugin_gc: PluginGcConfigs,
115}
116
117impl Default for Config {
118    fn default() -> Config {
119        Config {
120            show_banner: BannerKind::default(),
121
122            table: TableConfig::default(),
123            rm: RmConfig::default(),
124            ls: LsConfig::default(),
125
126            datetime_format: DatetimeFormatConfig::default(),
127
128            explore: defaults::default_explore(),
129            tui: defaults::default_tui(),
130
131            history: HistoryConfig::default(),
132
133            completions: CompletionConfig::default(),
134
135            recursion_limit: 50,
136
137            filesize: FilesizeConfig::default(),
138
139            cursor_shape: CursorShapeConfig::default(),
140
141            clip: ClipConfig::default(),
142
143            color_config: defaults::default_color_config(),
144            footer_mode: FooterMode::RowCount(25),
145            float_precision: 2,
146            buffer_editor: Value::nothing(Span::unknown()),
147            use_ansi_coloring: UseAnsiColoring::default(),
148            bracketed_paste: true,
149            edit_mode: EditBindings::default(),
150            show_hints: true,
151            hinter: HinterConfig::default(),
152            status_line: StatusLineConfig::default(),
153
154            shell_integration: ShellIntegrationConfig::default(),
155
156            render_right_prompt_on_last_line: false,
157
158            hooks: Hooks::new(),
159
160            menus: defaults::default_menus(),
161
162            keybindings: defaults::default_keybindings(),
163            abbreviations: HashMap::new(),
164
165            error_style: ErrorStyle::default(),
166            error_lines: 1,
167            display_errors: DisplayErrors::default(),
168
169            use_kitty_protocol: false,
170            highlight_resolved_externals: false,
171
172            auto_cd_implicit: false,
173            duration_max_unit: DurationMaxUnit::default(),
174
175            // Opt-in for `.last` payload: 0 drops last, keeps exit_code/duration/command.
176            max_last_result_size: Filesize::ZERO,
177
178            plugins: HashMap::new(),
179            plugin_gc: PluginGcConfigs::default(),
180        }
181    }
182}
183
184impl UpdateFromValue for Config {
185    fn update<'a>(
186        &mut self,
187        value: &'a Value,
188        path: &mut ConfigPath<'a>,
189        errors: &mut ConfigErrors,
190    ) {
191        let Value::Record { val: record, .. } = value else {
192            errors.type_mismatch(path, Type::record(), value);
193            return;
194        };
195
196        for (col, val) in record.iter() {
197            let current_path = &mut path.push(col);
198
199            match col.as_str() {
200                "ls" => self.ls.update(val, current_path, errors),
201                "rm" => self.rm.update(val, current_path, errors),
202                "history" => self.history.update(val, current_path, errors),
203                "completions" => self.completions.update(val, current_path, errors),
204                "cursor_shape" => self.cursor_shape.update(val, current_path, errors),
205                "table" => self.table.update(val, current_path, errors),
206                "filesize" => self.filesize.update(val, current_path, errors),
207                "explore" => self.explore.update(val, current_path, errors),
208                "tui" => {
209                    self.tui.update(val, current_path, errors);
210                    check_tui_border_type(&mut self.tui, current_path, errors);
211                }
212                "color_config" => self.color_config.update(val, current_path, errors),
213                "clip" => self.clip.update(val, current_path, errors),
214                "footer_mode" => self.footer_mode.update(val, current_path, errors),
215                "float_precision" => self.float_precision.update(val, current_path, errors),
216                "use_ansi_coloring" => self.use_ansi_coloring.update(val, current_path, errors),
217                "edit_mode" => self.edit_mode.update(val, current_path, errors),
218                "show_hints" => self.show_hints.update(val, current_path, errors),
219                "hinter" => self.hinter.update(val, current_path, errors),
220                "status_line" => self.status_line.update(val, current_path, errors),
221                "shell_integration" => self.shell_integration.update(val, current_path, errors),
222                "show_banner" => self.show_banner.update(val, current_path, errors),
223                "display_errors" => self.display_errors.update(val, current_path, errors),
224                "render_right_prompt_on_last_line" => {
225                    self.render_right_prompt_on_last_line
226                        .update(val, current_path, errors)
227                }
228                "bracketed_paste" => self.bracketed_paste.update(val, current_path, errors),
229                "use_kitty_protocol" => self.use_kitty_protocol.update(val, current_path, errors),
230                "highlight_resolved_externals" => {
231                    self.highlight_resolved_externals
232                        .update(val, current_path, errors)
233                }
234                "auto_cd_implicit" => self.auto_cd_implicit.update(val, current_path, errors),
235                "duration_max_unit" => self.duration_max_unit.update(val, current_path, errors),
236                "plugins" => self.plugins.update(val, current_path, errors),
237                "plugin_gc" => self.plugin_gc.update(val, current_path, errors),
238                "abbreviations" => self.abbreviations.update(val, current_path, errors),
239                "hooks" => self.hooks.update(val, current_path, errors),
240                "datetime_format" => self.datetime_format.update(val, current_path, errors),
241                "error_style" => self.error_style.update(val, current_path, errors),
242
243                "buffer_editor" => match val {
244                    Value::Nothing { .. } | Value::String { .. } => {
245                        self.buffer_editor = val.clone();
246                    }
247                    Value::List { vals: values, .. }
248                        if values
249                            .iter()
250                            .all(|list_element| matches!(list_element, Value::String { .. })) =>
251                    {
252                        self.buffer_editor = val.clone();
253                    }
254                    _ => errors.type_mismatch(
255                        current_path,
256                        Type::custom("string, list<string>, or nothing"),
257                        val,
258                    ),
259                },
260
261                "max_last_result_size" => {
262                    self.max_last_result_size.update(val, current_path, errors)
263                }
264
265                // Stored as written, like any list. Reedline registers the
266                // menus in order, so a later one wins on a name. A menu with a
267                // layout, input mode or output mode that can't be read rejects
268                // the whole list and the previous one stays, like for any other
269                // config value.
270                "menus" => match Vec::<ParsedMenu>::from_value(val.clone()).and_then(|menus| {
271                    menus.iter().try_for_each(|menu| menu.validate(self))?;
272                    Ok(menus)
273                }) {
274                    Ok(menus) => self.menus = menus,
275                    Err(error) => errors.error(error.into()),
276                },
277
278                // Stored as written, like any list. Reedline applies the
279                // entries in order, so a later one wins on a key. An entry
280                // with a mode, modifier or keycode that can't be read rejects
281                // the whole list and the previous one stays. Its `event` is
282                // read when the prompt is built.
283                "keybindings" => {
284                    match Vec::<ParsedKeybinding>::from_value(val.clone()).and_then(|keybindings| {
285                        keybindings
286                            .iter()
287                            .try_for_each(ParsedKeybinding::validate)?;
288                        Ok(keybindings)
289                    }) {
290                        Ok(keybindings) => self.keybindings = keybindings,
291                        Err(error) => errors.error(error.into()),
292                    }
293                }
294
295                "error_lines" => match val.as_int() {
296                    Ok(integer) if integer >= 0 => self.error_lines = integer,
297                    Ok(_) => {
298                        errors.invalid_value(current_path, "an int greater than or equal to 0", val)
299                    }
300                    Err(_) => errors.type_mismatch(current_path, Type::Int, val),
301                },
302
303                "recursion_limit" => match val.as_int() {
304                    Ok(integer) if integer > 1 => self.recursion_limit = integer,
305                    Ok(_) => errors.invalid_value(current_path, "an int greater than 1", val),
306                    Err(_) => errors.type_mismatch(current_path, Type::Int, val),
307                },
308
309                _ => errors.unknown_option(current_path, val),
310            }
311        }
312    }
313}
314
315/// `$env.config.tui` is a free-form map of colors, except `border_type`,
316/// which must name a tui border (see [`TableMode::from_tui_border`]). A bad
317/// value is reported here, where it is set, and the previous one is kept,
318/// like a typed field that fails to update.
319fn check_tui_border_type(
320    tui: &mut HashMap<String, Value>,
321    path: &mut ConfigPath,
322    errors: &mut ConfigErrors,
323) {
324    const KEY: &str = "border_type";
325    let Some(value) = tui.get(KEY) else {
326        return;
327    };
328    let path = &mut path.push(KEY);
329    match value.as_str() {
330        Ok(name) if TableMode::from_tui_border(name).is_some() => return,
331        Ok(_) => {
332            let names = TableMode::tui_border_names().collect::<Vec<_>>().join(", ");
333            errors.invalid_value(path, format!("one of {names}"), value);
334        }
335        Err(_) => errors.type_mismatch(path, Type::String, value),
336    }
337    match errors.config().tui.get(KEY).cloned() {
338        Some(old) => tui.insert(KEY.into(), old),
339        None => tui.remove(KEY),
340    };
341}
342
343impl UpdateFromValue for Filesize {
344    fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
345        match value.as_filesize() {
346            Ok(size) if !size.is_negative() => *self = size,
347            Ok(_) => errors.invalid_value(path, "a non-negative filesize", value),
348            Err(_) => errors.type_mismatch(path, Type::Filesize, value),
349        }
350    }
351}
352
353impl Config {
354    /// Returns the configured last-result size budget in bytes (`0` disables `.last` only).
355    pub fn max_last_result_size_bytes(&self) -> usize {
356        self.max_last_result_size.get().max(0) as usize
357    }
358
359    pub fn update_from_value(
360        &mut self,
361        old: &Config,
362        value: &Value,
363    ) -> Result<Option<ShellWarning>, ShellError> {
364        self.update_from_value_with_options(old, value, false)
365    }
366
367    /// Like [`Config::update_from_value`], but allows callers to indicate that runtime-locked
368    /// options should refuse to change.
369    ///
370    /// `history_locked_after_startup` should be set to `true` once the REPL has finished
371    /// initializing reedline's history backend. After that point, changing any of the
372    /// startup-only history fields (`path`, `max_size`, `file_format`, `isolation`) has no
373    /// effect on the live history, so we reject the assignment with a clear error instead of
374    /// silently ignoring it.
375    pub fn update_from_value_with_options(
376        &mut self,
377        old: &Config,
378        value: &Value,
379        history_locked_after_startup: bool,
380    ) -> Result<Option<ShellWarning>, ShellError> {
381        // Current behaviour is that config errors are displayed, but do not prevent the rest
382        // of the config from being updated (fields with errors are skipped/not updated).
383        // Errors are simply collected one-by-one and wrapped into a ShellError variant at the end.
384        let mut errors =
385            ConfigErrors::new(old).with_history_locked_after_startup(history_locked_after_startup);
386        let mut path = ConfigPath::new();
387
388        self.update(value, &mut path, &mut errors);
389
390        errors.check()
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    /// Run one `$env.config.menus = [...]` assignment.
399    fn assign_menus(config: &mut Config, old: &Config, menus: Vec<ParsedMenu>) {
400        try_assign_menus(config, old, menus).expect("update should succeed");
401    }
402
403    fn menu_names(config: &Config) -> Vec<String> {
404        config
405            .menus
406            .iter()
407            .map(|menu| menu.name.to_expanded_string("", config))
408            .collect()
409    }
410
411    /// `=` replaces the whole list, defaults included.
412    #[test]
413    fn assigning_menus_replaces_the_list() {
414        let old = Config::default();
415        let mut new = old.clone();
416
417        let mut extra = old.menus[0].clone();
418        extra.name = Value::test_string("added_menu");
419        assign_menus(&mut new, &old, vec![extra]);
420
421        assert_eq!(menu_names(&new), ["added_menu"]);
422    }
423
424    /// `++=` keeps the defaults and adds the new menu after them.
425    #[test]
426    fn appending_a_menu_keeps_the_defaults() {
427        let old = Config::default();
428        let mut new = old.clone();
429
430        let mut extra = old.menus[0].clone();
431        extra.name = Value::test_string("added_menu");
432        let mut menus = new.menus.clone();
433        menus.push(extra);
434        assign_menus(&mut new, &old, menus);
435
436        let mut expected = menu_names(&old);
437        expected.push("added_menu".into());
438        assert_eq!(menu_names(&new), expected);
439    }
440
441    /// The list is stored as written, so two menus with one name both stay and
442    /// keep their order. Reedline registers them in that order and the last
443    /// one wins, which is what makes `++=` with a default's name override it.
444    #[test]
445    fn menus_are_stored_as_written() {
446        let old = Config::default();
447        let mut new = old.clone();
448
449        let mut custom = old.menus[0].clone();
450        custom.marker = Value::test_string("custom> ");
451        let mut menus = new.menus.clone();
452        menus.push(custom);
453        assign_menus(&mut new, &old, menus);
454
455        let name = old.menus[0].name.to_expanded_string("", &old);
456        let same_name = |config: &Config| {
457            menu_names(config)
458                .iter()
459                .filter(|menu| **menu == name)
460                .count()
461        };
462        assert_eq!(same_name(&new), 2);
463        let last = new.menus.last().expect("menus are not empty");
464        assert_eq!(last.marker, Value::test_string("custom> "));
465    }
466
467    /// Assigning an empty list clears every menu.
468    #[test]
469    fn assigning_an_empty_list_clears_the_menus() {
470        let old = Config::default();
471        let mut new = old.clone();
472
473        assign_menus(&mut new, &old, vec![]);
474        assert!(new.menus.is_empty(), "`= []` should reset the list");
475    }
476
477    /// `tui.border_type` is checked where it is set: a name that is not a tui
478    /// border is an error and the previous border stays.
479    #[test]
480    fn tui_border_type_rejects_non_borders_and_keeps_the_old_one() {
481        let old = Config::default();
482        let tui = |border_type: Value| {
483            Value::test_record(record! {
484                "tui" => Value::test_record(record! { "border_type" => border_type }),
485            })
486        };
487
488        let mut new = old.clone();
489        new.update_from_value(&old, &tui(Value::test_string("Double")))
490            .expect("a table theme name is a border");
491        assert_eq!(
492            new.tui.get("border_type"),
493            Some(&Value::test_string("Double"))
494        );
495
496        for bad in [
497            Value::test_string("none"),
498            Value::test_string("default"),
499            Value::test_string("wavy"),
500            Value::test_int(1),
501        ] {
502            let mut new = old.clone();
503            let err = new
504                .update_from_value(&old, &tui(bad.clone()))
505                .expect_err("not a tui border");
506            assert!(
507                format!("{err:?}").contains("$env.config.tui.border_type"),
508                "{bad:?}: {err:?}"
509            );
510            assert_eq!(new.tui.get("border_type"), old.tui.get("border_type"));
511        }
512    }
513
514    /// `TableMode::NAMES` feeds `table --theme` and `tui --border`
515    /// completions, so it must hold every name `from_str` accepts: the ones
516    /// its error lists, plus `default`.
517    #[test]
518    fn table_mode_names_match_from_str() {
519        for name in TableMode::NAMES {
520            assert!(name.parse::<TableMode>().is_ok(), "{name}");
521        }
522        let listed = "wavy".parse::<TableMode>().expect_err("not a table mode");
523        let listed: Vec<&str> = listed.split('\'').skip(1).step_by(2).collect();
524        for name in &listed {
525            assert!(TableMode::NAMES.contains(name), "{name} is not in NAMES");
526        }
527        assert_eq!(listed.len() + 1, TableMode::NAMES.len());
528    }
529
530    // --- keybindings: a plain list, applied in order by reedline ---
531
532    fn keybinding(
533        name: Option<&str>,
534        modifier: &str,
535        keycode: &str,
536        mode: Value,
537    ) -> ParsedKeybinding {
538        ParsedKeybinding {
539            name: name.map(Value::test_string),
540            modifier: Value::test_string(modifier),
541            keycode: Value::test_string(keycode),
542            event: Value::test_nothing(),
543            mode,
544        }
545    }
546
547    fn atuin() -> ParsedKeybinding {
548        keybinding(
549            Some("atuin"),
550            "control",
551            "char_r",
552            Value::test_string("emacs"),
553        )
554    }
555
556    /// Run one `$env.config.keybindings = [...]` assignment.
557    fn assign(config: &mut Config, old: &Config, keybindings: Vec<ParsedKeybinding>) {
558        try_assign(config, old, keybindings).expect("update should succeed");
559    }
560
561    /// `$env.config.keybindings ++= [...]` is `= ($env.config.keybindings ++ [...])`.
562    fn append(config: &mut Config, old: &Config, keybindings: Vec<ParsedKeybinding>) {
563        let mut list = config.keybindings.clone();
564        list.extend(keybindings);
565        assign(config, old, list);
566    }
567
568    fn count_named(config: &Config, name: &str) -> usize {
569        config
570            .keybindings
571            .iter()
572            .filter(|kb| {
573                kb.name
574                    .as_ref()
575                    .is_some_and(|n| n.to_expanded_string("", config) == name)
576            })
577            .count()
578    }
579
580    /// `=` replaces the whole list, defaults included.
581    #[test]
582    fn assigning_keybindings_replaces_the_list() {
583        let old = Config::default();
584        let mut new = old.clone();
585
586        assign(&mut new, &old, vec![atuin()]);
587
588        assert_eq!(new.keybindings.len(), 1);
589        assert_eq!(count_named(&new, "atuin"), 1);
590    }
591
592    /// `++=` keeps the defaults and adds the new binding after them.
593    #[test]
594    fn appending_keeps_the_defaults() {
595        let old = Config::default();
596        let mut new = old.clone();
597
598        append(&mut new, &old, vec![atuin()]);
599
600        assert_eq!(new.keybindings.len(), old.keybindings.len() + 1);
601        assert_eq!(count_named(&new, "atuin"), 1);
602        assert_eq!(count_named(&new, "history_menu"), 1);
603    }
604
605    /// Filtering a binding out of the list unbinds it.
606    #[test]
607    fn assigning_a_filtered_list_drops_the_binding() {
608        let old = Config::default();
609        let mut new = old.clone();
610        append(&mut new, &old, vec![atuin()]);
611        let len = new.keybindings.len();
612
613        let kept = new
614            .keybindings
615            .iter()
616            .filter(|kb| {
617                kb.name
618                    .as_ref()
619                    .is_none_or(|n| n.to_expanded_string("", &new) != "atuin")
620            })
621            .cloned()
622            .collect();
623        assign(&mut new, &old, kept);
624
625        assert_eq!(count_named(&new, "atuin"), 0);
626        assert_eq!(new.keybindings.len(), len - 1);
627    }
628
629    /// Assigning an empty list clears every binding.
630    #[test]
631    fn assigning_an_empty_list_clears_the_keybindings() {
632        let old = Config::default();
633        let mut new = old.clone();
634
635        assign(&mut new, &old, vec![]);
636        assert!(new.keybindings.is_empty(), "`= []` should reset the list");
637    }
638
639    /// The list is stored as written, so entries that bind the same key stay
640    /// and keep their order. Reedline applies them in that order, thus the
641    /// last one wins.
642    #[test]
643    fn the_list_is_stored_as_written() {
644        let old = Config::default();
645        let mut new = old.clone();
646
647        let mut first = atuin();
648        first.event = Value::test_string("first");
649        let mut second = atuin();
650        second.event = Value::test_string("second");
651        assign(&mut new, &old, vec![first, second]);
652
653        assert_eq!(new.keybindings.len(), 2);
654        assert_eq!(new.keybindings[0].event, Value::test_string("first"));
655        assert_eq!(new.keybindings[1].event, Value::test_string("second"));
656    }
657
658    /// The atuin case (nushell/nushell#18848): one name on two keys is two
659    /// bindings.
660    #[test]
661    fn a_shared_name_on_different_keys_keeps_both_bindings() {
662        let old = Config::default();
663        let mut new = old.clone();
664
665        append(
666            &mut new,
667            &old,
668            vec![
669                atuin(),
670                keybinding(Some("atuin"), "none", "up", Value::test_string("emacs")),
671            ],
672        );
673
674        assert_eq!(count_named(&new, "atuin"), 2);
675    }
676
677    // --- an entry that cannot be read rejects the whole list ---
678
679    /// Run one `$env.config.<field> = [...]` assignment that may be rejected.
680    fn try_assign_list<T: IntoValue>(
681        config: &mut Config,
682        old: &Config,
683        field: &str,
684        items: Vec<T>,
685    ) -> Result<(), ShellError> {
686        let list = Value::test_list(
687            items
688                .into_iter()
689                .map(|item| item.into_value(Span::test_data()))
690                .collect(),
691        );
692        let value = Value::test_record(record! { field => list });
693        config.update_from_value(old, &value).map(drop)
694    }
695
696    /// Run one `$env.config.keybindings = [...]` assignment that may be rejected.
697    fn try_assign(
698        config: &mut Config,
699        old: &Config,
700        keybindings: Vec<ParsedKeybinding>,
701    ) -> Result<(), ShellError> {
702        try_assign_list(config, old, "keybindings", keybindings)
703    }
704
705    /// Run one `$env.config.menus = [...]` assignment that may be rejected.
706    fn try_assign_menus(
707        config: &mut Config,
708        old: &Config,
709        menus: Vec<ParsedMenu>,
710    ) -> Result<(), ShellError> {
711        try_assign_list(config, old, "menus", menus)
712    }
713
714    /// One bad entry among good ones: the list is rejected and the old one stays,
715    /// like `table.mode = "bogus"` keeps the old mode.
716    #[test]
717    fn an_entry_that_cannot_be_read_rejects_the_whole_list() {
718        let old = Config::default();
719        let emacs = Value::test_string("emacs");
720        let faulty = [
721            keybinding(Some("bad_key"), "control", "nonsense", emacs.clone()),
722            keybinding(Some("bad_modifier"), "bogus", "char_t", emacs),
723            keybinding(
724                Some("bad_mode"),
725                "control",
726                "char_t",
727                Value::test_string("bogus"),
728            ),
729            keybinding(
730                Some("bad_char"),
731                "control",
732                "char_ab",
733                Value::test_string("emacs"),
734            ),
735        ];
736
737        for bad in faulty {
738            let name = bad
739                .name
740                .as_ref()
741                .map(|name| name.to_expanded_string("", &old));
742            let mut new = old.clone();
743            let result = try_assign(&mut new, &old, vec![atuin(), bad]);
744
745            assert!(result.is_err(), "{name:?} was accepted");
746            assert_eq!(
747                new.keybindings.len(),
748                old.keybindings.len(),
749                "{name:?} changed the list"
750            );
751            assert_eq!(
752                count_named(&new, "atuin"),
753                0,
754                "{name:?} let a good entry through"
755            );
756        }
757    }
758
759    /// The scenario from a reload: a broken entry is appended, then the fixed
760    /// config appends a good one. Only the good one ends up in the list.
761    #[test]
762    fn a_fixed_entry_appended_after_a_rejected_one_is_accepted() {
763        let old = Config::default();
764        let mut new = old.clone();
765        let broken = || {
766            keybinding(
767                Some("mine"),
768                "control",
769                "nonsense",
770                Value::test_string("emacs"),
771            )
772        };
773        let fixed = || {
774            keybinding(
775                Some("mine"),
776                "control",
777                "char_t",
778                Value::test_string("emacs"),
779            )
780        };
781
782        let mut list = new.keybindings.clone();
783        list.push(broken());
784        assert!(try_assign(&mut new, &old, list).is_err());
785        assert_eq!(new.keybindings.len(), old.keybindings.len());
786
787        let mut list = new.keybindings.clone();
788        list.push(fixed());
789        assert!(try_assign(&mut new, &old, list).is_ok());
790        assert_eq!(count_named(&new, "mine"), 1);
791    }
792
793    /// A rejected list is not a rejected config: other fields in the same
794    /// record are still applied, as for any other value that can't be read.
795    #[test]
796    fn a_rejected_list_does_not_stop_other_fields() {
797        let old = Config::default();
798        let mut new = old.clone();
799        let bad = keybinding(
800            Some("bad"),
801            "control",
802            "nonsense",
803            Value::test_string("emacs"),
804        );
805        let value = Value::test_record(record! {
806            "keybindings" => Value::test_list(vec![bad.into_value(Span::test_data())]),
807            "error_lines" => Value::test_int(old.error_lines + 3),
808        });
809
810        assert!(new.update_from_value(&old, &value).is_err());
811        assert_eq!(new.error_lines, old.error_lines + 3);
812        assert_eq!(new.keybindings.len(), old.keybindings.len());
813    }
814
815    /// An event needs reedline's types to be read, so it is read when the prompt
816    /// is built and not when the list is assigned.
817    #[test]
818    fn an_event_is_not_checked_on_assignment() {
819        let old = Config::default();
820        let mut new = old.clone();
821        let mut entry = atuin();
822        entry.event = Value::test_record(record! { "send" => Value::test_string("bogus") });
823
824        assert!(try_assign(&mut new, &old, vec![entry]).is_ok());
825        assert_eq!(new.keybindings.len(), 1);
826    }
827
828    /// Entries without any mode bind nothing, but the key is checked all the same.
829    #[test]
830    fn an_entry_with_no_mode_still_needs_a_key_that_can_be_read() {
831        let old = Config::default();
832        let no_modes = Value::test_list(vec![]);
833
834        let mut new = old.clone();
835        let readable = keybinding(Some("idle"), "control", "char_t", no_modes.clone());
836        assert!(try_assign(&mut new, &old, vec![readable]).is_ok());
837
838        let mut new = old.clone();
839        let unreadable = keybinding(Some("idle"), "control", "nonsense", no_modes);
840        assert!(try_assign(&mut new, &old, vec![unreadable]).is_err());
841        assert_eq!(new.keybindings.len(), old.keybindings.len());
842    }
843
844    /// A menu whose layout can't be read rejects the whole list too.
845    #[test]
846    fn a_menu_that_cannot_be_read_rejects_the_whole_list() {
847        let old = Config::default();
848
849        let mut grid = old.menus[0].clone();
850        grid.name = Value::test_string("grid_menu");
851        grid.r#type = Value::test_record(record! { "layout" => Value::test_string("grid") });
852        let mut no_layout = grid.clone();
853        no_layout.r#type = Value::test_record(record! {});
854        let mut not_a_record = grid.clone();
855        not_a_record.r#type = Value::test_string("columnar");
856
857        // The modes are read on assignment too, not only the layout.
858        let mut bad_input_mode = old.menus[0].clone();
859        bad_input_mode.input_mode = Some(Value::test_string("bogus"));
860        let mut no_input_mode = old.menus[0].clone();
861        no_input_mode.input_mode = None;
862        no_input_mode.only_buffer_difference = None;
863        let mut bad_flag = no_input_mode.clone();
864        bad_flag.only_buffer_difference = Some(Value::test_int(3));
865        let mut bad_output_mode = old.menus[0].clone();
866        bad_output_mode.output_mode = Some(Value::test_string("bogus"));
867
868        for bad in [
869            grid,
870            no_layout,
871            not_a_record,
872            bad_input_mode,
873            no_input_mode,
874            bad_flag,
875            bad_output_mode,
876        ] {
877            let mut new = old.clone();
878            let good = old.menus[0].clone();
879            let result = try_assign_menus(&mut new, &old, vec![good, bad]);
880
881            assert!(result.is_err());
882            assert_eq!(menu_names(&new), menu_names(&old));
883        }
884    }
885}