Skip to main content

fresh/
partial_config.rs

1//! Partial configuration types for layered config merging.
2//!
3//! This module provides `Option`-wrapped versions of all config structs,
4//! enabling a 4-level overlay architecture (System → User → Project → Session).
5
6use crate::config::{
7    ClipboardConfig, CursorStyle, FileBrowserConfig, FileExplorerConfig, FormatterConfig,
8    HighlighterPreference, Keybinding, KeybindingMapName, KeymapConfig, LanguageConfig,
9    LineEndingOption, OnSaveAction, PluginConfig, TerminalConfig, ThemeName, WarningsConfig,
10};
11use crate::types::LspLanguageConfig;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14
15/// Trait for merging configuration layers.
16/// Higher precedence values (self) override lower precedence (other).
17pub trait Merge {
18    /// Merge values from a lower-precedence layer into this layer.
19    /// Values already set in self take precedence over values in other.
20    fn merge_from(&mut self, other: &Self);
21}
22
23impl<T: Clone> Merge for Option<T> {
24    fn merge_from(&mut self, other: &Self) {
25        if self.is_none() {
26            *self = other.clone();
27        }
28    }
29}
30
31/// Merge two HashMaps where self's entries take precedence.
32/// Entries from other are added if not present in self.
33fn merge_hashmap<K: Clone + Eq + std::hash::Hash, V: Clone>(
34    target: &mut Option<HashMap<K, V>>,
35    other: &Option<HashMap<K, V>>,
36) {
37    match (target, other) {
38        (Some(t), Some(o)) => {
39            for (key, value) in o {
40                t.entry(key.clone()).or_insert_with(|| value.clone());
41            }
42        }
43        (t @ None, Some(o)) => {
44            *t = Some(o.clone());
45        }
46        _ => {}
47    }
48}
49
50/// Merge two HashMaps where values implement Merge (for recursive merging).
51fn merge_hashmap_recursive<K, V>(target: &mut Option<HashMap<K, V>>, other: &Option<HashMap<K, V>>)
52where
53    K: Clone + Eq + std::hash::Hash,
54    V: Clone + Merge + Default,
55{
56    match (target, other) {
57        (Some(t), Some(o)) => {
58            for (key, value) in o {
59                t.entry(key.clone())
60                    .and_modify(|existing| existing.merge_from(value))
61                    .or_insert_with(|| value.clone());
62            }
63        }
64        (t @ None, Some(o)) => {
65            *t = Some(o.clone());
66        }
67        _ => {}
68    }
69}
70
71/// Partial configuration where all fields are optional.
72/// Represents a single configuration layer (User, Project, or Session).
73#[derive(Debug, Clone, Default, Deserialize, Serialize)]
74#[serde(default)]
75pub struct PartialConfig {
76    pub version: Option<u32>,
77    pub theme: Option<ThemeName>,
78    pub locale: Option<String>,
79    pub check_for_updates: Option<bool>,
80    pub editor: Option<PartialEditorConfig>,
81    pub file_explorer: Option<PartialFileExplorerConfig>,
82    pub file_browser: Option<PartialFileBrowserConfig>,
83    pub clipboard: Option<PartialClipboardConfig>,
84    pub terminal: Option<PartialTerminalConfig>,
85    pub keybindings: Option<Vec<Keybinding>>,
86    pub keybinding_maps: Option<HashMap<String, KeymapConfig>>,
87    pub active_keybinding_map: Option<KeybindingMapName>,
88    pub languages: Option<HashMap<String, PartialLanguageConfig>>,
89    pub fallback: Option<LanguageConfig>,
90    pub lsp: Option<HashMap<String, LspLanguageConfig>>,
91    pub warnings: Option<PartialWarningsConfig>,
92    pub plugins: Option<HashMap<String, PartialPluginConfig>>,
93    pub packages: Option<PartialPackagesConfig>,
94}
95
96impl Merge for PartialConfig {
97    fn merge_from(&mut self, other: &Self) {
98        self.version.merge_from(&other.version);
99        self.theme.merge_from(&other.theme);
100        self.locale.merge_from(&other.locale);
101        self.check_for_updates.merge_from(&other.check_for_updates);
102
103        // Nested structs: merge recursively
104        merge_partial(&mut self.editor, &other.editor);
105        merge_partial(&mut self.file_explorer, &other.file_explorer);
106        merge_partial(&mut self.file_browser, &other.file_browser);
107        merge_partial(&mut self.clipboard, &other.clipboard);
108        merge_partial(&mut self.terminal, &other.terminal);
109        merge_partial(&mut self.warnings, &other.warnings);
110        merge_partial(&mut self.packages, &other.packages);
111
112        // Lists: higher precedence replaces (per design doc)
113        self.keybindings.merge_from(&other.keybindings);
114
115        // HashMaps: merge entries, higher precedence wins on key collision
116        merge_hashmap(&mut self.keybinding_maps, &other.keybinding_maps);
117        merge_hashmap_recursive(&mut self.languages, &other.languages);
118        self.fallback.merge_from(&other.fallback);
119        merge_hashmap(&mut self.lsp, &other.lsp);
120        merge_hashmap_recursive(&mut self.plugins, &other.plugins);
121
122        self.active_keybinding_map
123            .merge_from(&other.active_keybinding_map);
124    }
125}
126
127/// Helper to merge nested partial structs.
128fn merge_partial<T: Merge + Clone>(target: &mut Option<T>, other: &Option<T>) {
129    match (target, other) {
130        (Some(t), Some(o)) => t.merge_from(o),
131        (t @ None, Some(o)) => *t = Some(o.clone()),
132        _ => {}
133    }
134}
135
136/// Partial editor configuration.
137#[derive(Debug, Clone, Default, Deserialize, Serialize)]
138#[serde(default)]
139pub struct PartialEditorConfig {
140    pub use_tabs: Option<bool>,
141    pub tab_size: Option<usize>,
142    pub auto_indent: Option<bool>,
143    pub auto_close: Option<bool>,
144    pub auto_surround: Option<bool>,
145    pub line_numbers: Option<bool>,
146    pub relative_line_numbers: Option<bool>,
147    pub scroll_offset: Option<usize>,
148    pub syntax_highlighting: Option<bool>,
149    pub highlight_current_line: Option<bool>,
150    pub line_wrap: Option<bool>,
151    pub wrap_indent: Option<bool>,
152    pub wrap_column: Option<Option<usize>>,
153    pub page_width: Option<Option<usize>>,
154    pub highlight_timeout_ms: Option<u64>,
155    pub snapshot_interval: Option<usize>,
156    pub large_file_threshold_bytes: Option<u64>,
157    pub estimated_line_length: Option<usize>,
158    pub enable_inlay_hints: Option<bool>,
159    pub enable_semantic_tokens_full: Option<bool>,
160    pub diagnostics_inline_text: Option<bool>,
161    pub recovery_enabled: Option<bool>,
162    pub auto_recovery_save_interval_secs: Option<u32>,
163    pub auto_save_enabled: Option<bool>,
164    pub auto_save_interval_secs: Option<u32>,
165    pub hot_exit: Option<bool>,
166    pub highlight_context_bytes: Option<usize>,
167    pub mouse_hover_enabled: Option<bool>,
168    pub mouse_hover_delay_ms: Option<u64>,
169    pub double_click_time_ms: Option<u64>,
170    pub auto_revert_poll_interval_ms: Option<u64>,
171    pub read_concurrency: Option<usize>,
172    pub file_tree_poll_interval_ms: Option<u64>,
173    pub default_line_ending: Option<LineEndingOption>,
174    pub trim_trailing_whitespace_on_save: Option<bool>,
175    pub ensure_final_newline_on_save: Option<bool>,
176    pub highlight_matching_brackets: Option<bool>,
177    pub rainbow_brackets: Option<bool>,
178    pub cursor_style: Option<CursorStyle>,
179    pub keyboard_disambiguate_escape_codes: Option<bool>,
180    pub keyboard_report_event_types: Option<bool>,
181    pub keyboard_report_alternate_keys: Option<bool>,
182    pub keyboard_report_all_keys_as_escape_codes: Option<bool>,
183    pub completion_popup_auto_show: Option<bool>,
184    pub quick_suggestions: Option<bool>,
185    pub quick_suggestions_delay_ms: Option<u64>,
186    pub suggest_on_trigger_characters: Option<bool>,
187    pub show_menu_bar: Option<bool>,
188    pub menu_bar_mnemonics: Option<bool>,
189    pub show_tab_bar: Option<bool>,
190    pub show_status_bar: Option<bool>,
191    pub show_prompt_line: Option<bool>,
192    pub show_vertical_scrollbar: Option<bool>,
193    pub show_horizontal_scrollbar: Option<bool>,
194    pub show_tilde: Option<bool>,
195    pub use_terminal_bg: Option<bool>,
196    pub rulers: Option<Vec<usize>>,
197    pub whitespace_show: Option<bool>,
198    pub whitespace_spaces_leading: Option<bool>,
199    pub whitespace_spaces_inner: Option<bool>,
200    pub whitespace_spaces_trailing: Option<bool>,
201    pub whitespace_tabs_leading: Option<bool>,
202    pub whitespace_tabs_inner: Option<bool>,
203    pub whitespace_tabs_trailing: Option<bool>,
204}
205
206impl Merge for PartialEditorConfig {
207    fn merge_from(&mut self, other: &Self) {
208        self.use_tabs.merge_from(&other.use_tabs);
209        self.tab_size.merge_from(&other.tab_size);
210        self.auto_indent.merge_from(&other.auto_indent);
211        self.auto_close.merge_from(&other.auto_close);
212        self.auto_surround.merge_from(&other.auto_surround);
213        self.line_numbers.merge_from(&other.line_numbers);
214        self.relative_line_numbers
215            .merge_from(&other.relative_line_numbers);
216        self.scroll_offset.merge_from(&other.scroll_offset);
217        self.syntax_highlighting
218            .merge_from(&other.syntax_highlighting);
219        self.line_wrap.merge_from(&other.line_wrap);
220        self.wrap_indent.merge_from(&other.wrap_indent);
221        self.wrap_column.merge_from(&other.wrap_column);
222        self.page_width.merge_from(&other.page_width);
223        self.highlight_timeout_ms
224            .merge_from(&other.highlight_timeout_ms);
225        self.snapshot_interval.merge_from(&other.snapshot_interval);
226        self.large_file_threshold_bytes
227            .merge_from(&other.large_file_threshold_bytes);
228        self.estimated_line_length
229            .merge_from(&other.estimated_line_length);
230        self.enable_inlay_hints
231            .merge_from(&other.enable_inlay_hints);
232        self.enable_semantic_tokens_full
233            .merge_from(&other.enable_semantic_tokens_full);
234        self.diagnostics_inline_text
235            .merge_from(&other.diagnostics_inline_text);
236        self.recovery_enabled.merge_from(&other.recovery_enabled);
237        self.auto_recovery_save_interval_secs
238            .merge_from(&other.auto_recovery_save_interval_secs);
239        self.auto_save_enabled.merge_from(&other.auto_save_enabled);
240        self.auto_save_interval_secs
241            .merge_from(&other.auto_save_interval_secs);
242        self.hot_exit.merge_from(&other.hot_exit);
243        self.highlight_context_bytes
244            .merge_from(&other.highlight_context_bytes);
245        self.mouse_hover_enabled
246            .merge_from(&other.mouse_hover_enabled);
247        self.mouse_hover_delay_ms
248            .merge_from(&other.mouse_hover_delay_ms);
249        self.double_click_time_ms
250            .merge_from(&other.double_click_time_ms);
251        self.auto_revert_poll_interval_ms
252            .merge_from(&other.auto_revert_poll_interval_ms);
253        self.read_concurrency.merge_from(&other.read_concurrency);
254        self.file_tree_poll_interval_ms
255            .merge_from(&other.file_tree_poll_interval_ms);
256        self.default_line_ending
257            .merge_from(&other.default_line_ending);
258        self.trim_trailing_whitespace_on_save
259            .merge_from(&other.trim_trailing_whitespace_on_save);
260        self.ensure_final_newline_on_save
261            .merge_from(&other.ensure_final_newline_on_save);
262        self.highlight_matching_brackets
263            .merge_from(&other.highlight_matching_brackets);
264        self.rainbow_brackets.merge_from(&other.rainbow_brackets);
265        self.cursor_style.merge_from(&other.cursor_style);
266        self.keyboard_disambiguate_escape_codes
267            .merge_from(&other.keyboard_disambiguate_escape_codes);
268        self.keyboard_report_event_types
269            .merge_from(&other.keyboard_report_event_types);
270        self.keyboard_report_alternate_keys
271            .merge_from(&other.keyboard_report_alternate_keys);
272        self.keyboard_report_all_keys_as_escape_codes
273            .merge_from(&other.keyboard_report_all_keys_as_escape_codes);
274        self.completion_popup_auto_show
275            .merge_from(&other.completion_popup_auto_show);
276        self.quick_suggestions.merge_from(&other.quick_suggestions);
277        self.quick_suggestions_delay_ms
278            .merge_from(&other.quick_suggestions_delay_ms);
279        self.suggest_on_trigger_characters
280            .merge_from(&other.suggest_on_trigger_characters);
281        self.show_menu_bar.merge_from(&other.show_menu_bar);
282        self.menu_bar_mnemonics
283            .merge_from(&other.menu_bar_mnemonics);
284        self.show_tab_bar.merge_from(&other.show_tab_bar);
285        self.show_status_bar.merge_from(&other.show_status_bar);
286        self.show_prompt_line.merge_from(&other.show_prompt_line);
287        self.show_vertical_scrollbar
288            .merge_from(&other.show_vertical_scrollbar);
289        self.show_horizontal_scrollbar
290            .merge_from(&other.show_horizontal_scrollbar);
291        self.show_tilde.merge_from(&other.show_tilde);
292        self.use_terminal_bg.merge_from(&other.use_terminal_bg);
293        self.rulers.merge_from(&other.rulers);
294        self.whitespace_show.merge_from(&other.whitespace_show);
295        self.whitespace_spaces_leading
296            .merge_from(&other.whitespace_spaces_leading);
297        self.whitespace_spaces_inner
298            .merge_from(&other.whitespace_spaces_inner);
299        self.whitespace_spaces_trailing
300            .merge_from(&other.whitespace_spaces_trailing);
301        self.whitespace_tabs_leading
302            .merge_from(&other.whitespace_tabs_leading);
303        self.whitespace_tabs_inner
304            .merge_from(&other.whitespace_tabs_inner);
305        self.whitespace_tabs_trailing
306            .merge_from(&other.whitespace_tabs_trailing);
307    }
308}
309
310/// Partial file explorer configuration.
311#[derive(Debug, Clone, Default, Deserialize, Serialize)]
312#[serde(default)]
313pub struct PartialFileExplorerConfig {
314    pub respect_gitignore: Option<bool>,
315    pub show_hidden: Option<bool>,
316    pub show_gitignored: Option<bool>,
317    pub custom_ignore_patterns: Option<Vec<String>>,
318    pub width: Option<f32>,
319}
320
321impl Merge for PartialFileExplorerConfig {
322    fn merge_from(&mut self, other: &Self) {
323        self.respect_gitignore.merge_from(&other.respect_gitignore);
324        self.show_hidden.merge_from(&other.show_hidden);
325        self.show_gitignored.merge_from(&other.show_gitignored);
326        self.custom_ignore_patterns
327            .merge_from(&other.custom_ignore_patterns);
328        self.width.merge_from(&other.width);
329    }
330}
331
332/// Partial file browser configuration.
333#[derive(Debug, Clone, Default, Deserialize, Serialize)]
334#[serde(default)]
335pub struct PartialFileBrowserConfig {
336    pub show_hidden: Option<bool>,
337}
338
339impl Merge for PartialFileBrowserConfig {
340    fn merge_from(&mut self, other: &Self) {
341        self.show_hidden.merge_from(&other.show_hidden);
342    }
343}
344
345/// Partial clipboard configuration.
346#[derive(Debug, Clone, Default, Deserialize, Serialize)]
347#[serde(default)]
348pub struct PartialClipboardConfig {
349    pub use_osc52: Option<bool>,
350    pub use_system_clipboard: Option<bool>,
351}
352
353impl Merge for PartialClipboardConfig {
354    fn merge_from(&mut self, other: &Self) {
355        self.use_osc52.merge_from(&other.use_osc52);
356        self.use_system_clipboard
357            .merge_from(&other.use_system_clipboard);
358    }
359}
360
361/// Partial terminal configuration.
362#[derive(Debug, Clone, Default, Deserialize, Serialize)]
363#[serde(default)]
364pub struct PartialTerminalConfig {
365    pub jump_to_end_on_output: Option<bool>,
366}
367
368impl Merge for PartialTerminalConfig {
369    fn merge_from(&mut self, other: &Self) {
370        self.jump_to_end_on_output
371            .merge_from(&other.jump_to_end_on_output);
372    }
373}
374
375/// Partial warnings configuration.
376#[derive(Debug, Clone, Default, Deserialize, Serialize)]
377#[serde(default)]
378pub struct PartialWarningsConfig {
379    pub show_status_indicator: Option<bool>,
380}
381
382impl Merge for PartialWarningsConfig {
383    fn merge_from(&mut self, other: &Self) {
384        self.show_status_indicator
385            .merge_from(&other.show_status_indicator);
386    }
387}
388
389/// Partial packages configuration for plugin/theme package management.
390#[derive(Debug, Clone, Default, Deserialize, Serialize)]
391#[serde(default)]
392pub struct PartialPackagesConfig {
393    pub sources: Option<Vec<String>>,
394}
395
396impl Merge for PartialPackagesConfig {
397    fn merge_from(&mut self, other: &Self) {
398        self.sources.merge_from(&other.sources);
399    }
400}
401
402/// Partial plugin configuration.
403#[derive(Debug, Clone, Default, Deserialize, Serialize)]
404#[serde(default)]
405pub struct PartialPluginConfig {
406    #[serde(skip_serializing_if = "Option::is_none")]
407    pub enabled: Option<bool>,
408    #[serde(skip_serializing_if = "Option::is_none")]
409    pub path: Option<std::path::PathBuf>,
410}
411
412impl Merge for PartialPluginConfig {
413    fn merge_from(&mut self, other: &Self) {
414        self.enabled.merge_from(&other.enabled);
415        self.path.merge_from(&other.path);
416    }
417}
418
419/// Partial language configuration.
420#[derive(Debug, Clone, Default, Deserialize, Serialize)]
421#[serde(default)]
422pub struct PartialLanguageConfig {
423    pub extensions: Option<Vec<String>>,
424    pub filenames: Option<Vec<String>>,
425    pub grammar: Option<String>,
426    pub comment_prefix: Option<String>,
427    pub auto_indent: Option<bool>,
428    pub auto_close: Option<bool>,
429    pub auto_surround: Option<bool>,
430    pub highlighter: Option<HighlighterPreference>,
431    pub textmate_grammar: Option<std::path::PathBuf>,
432    pub show_whitespace_tabs: Option<bool>,
433    pub line_wrap: Option<bool>,
434    pub wrap_column: Option<Option<usize>>,
435    pub page_view: Option<bool>,
436    pub page_width: Option<Option<usize>>,
437    pub use_tabs: Option<bool>,
438    pub tab_size: Option<usize>,
439    pub formatter: Option<FormatterConfig>,
440    pub format_on_save: Option<bool>,
441    pub on_save: Option<Vec<OnSaveAction>>,
442    pub word_characters: Option<Option<String>>,
443}
444
445impl Merge for PartialLanguageConfig {
446    fn merge_from(&mut self, other: &Self) {
447        self.extensions.merge_from(&other.extensions);
448        self.filenames.merge_from(&other.filenames);
449        self.grammar.merge_from(&other.grammar);
450        self.comment_prefix.merge_from(&other.comment_prefix);
451        self.auto_indent.merge_from(&other.auto_indent);
452        self.auto_close.merge_from(&other.auto_close);
453        self.auto_surround.merge_from(&other.auto_surround);
454        self.highlighter.merge_from(&other.highlighter);
455        self.textmate_grammar.merge_from(&other.textmate_grammar);
456        self.show_whitespace_tabs
457            .merge_from(&other.show_whitespace_tabs);
458        self.line_wrap.merge_from(&other.line_wrap);
459        self.wrap_column.merge_from(&other.wrap_column);
460        self.page_view.merge_from(&other.page_view);
461        self.page_width.merge_from(&other.page_width);
462        self.use_tabs.merge_from(&other.use_tabs);
463        self.tab_size.merge_from(&other.tab_size);
464        self.formatter.merge_from(&other.formatter);
465        self.format_on_save.merge_from(&other.format_on_save);
466        self.on_save.merge_from(&other.on_save);
467        self.word_characters.merge_from(&other.word_characters);
468    }
469}
470
471// Conversion traits for resolving partial configs to concrete configs
472
473impl From<&crate::config::EditorConfig> for PartialEditorConfig {
474    fn from(cfg: &crate::config::EditorConfig) -> Self {
475        Self {
476            use_tabs: Some(cfg.use_tabs),
477            tab_size: Some(cfg.tab_size),
478            auto_indent: Some(cfg.auto_indent),
479            auto_close: Some(cfg.auto_close),
480            auto_surround: Some(cfg.auto_surround),
481            line_numbers: Some(cfg.line_numbers),
482            relative_line_numbers: Some(cfg.relative_line_numbers),
483            scroll_offset: Some(cfg.scroll_offset),
484            syntax_highlighting: Some(cfg.syntax_highlighting),
485            highlight_current_line: Some(cfg.highlight_current_line),
486            line_wrap: Some(cfg.line_wrap),
487            wrap_indent: Some(cfg.wrap_indent),
488            wrap_column: Some(cfg.wrap_column),
489            page_width: Some(cfg.page_width),
490            highlight_timeout_ms: Some(cfg.highlight_timeout_ms),
491            snapshot_interval: Some(cfg.snapshot_interval),
492            large_file_threshold_bytes: Some(cfg.large_file_threshold_bytes),
493            estimated_line_length: Some(cfg.estimated_line_length),
494            enable_inlay_hints: Some(cfg.enable_inlay_hints),
495            enable_semantic_tokens_full: Some(cfg.enable_semantic_tokens_full),
496            diagnostics_inline_text: Some(cfg.diagnostics_inline_text),
497            recovery_enabled: Some(cfg.recovery_enabled),
498            auto_recovery_save_interval_secs: Some(cfg.auto_recovery_save_interval_secs),
499            auto_save_enabled: Some(cfg.auto_save_enabled),
500            auto_save_interval_secs: Some(cfg.auto_save_interval_secs),
501            hot_exit: Some(cfg.hot_exit),
502            highlight_context_bytes: Some(cfg.highlight_context_bytes),
503            mouse_hover_enabled: Some(cfg.mouse_hover_enabled),
504            mouse_hover_delay_ms: Some(cfg.mouse_hover_delay_ms),
505            double_click_time_ms: Some(cfg.double_click_time_ms),
506            auto_revert_poll_interval_ms: Some(cfg.auto_revert_poll_interval_ms),
507            read_concurrency: Some(cfg.read_concurrency),
508            file_tree_poll_interval_ms: Some(cfg.file_tree_poll_interval_ms),
509            default_line_ending: Some(cfg.default_line_ending.clone()),
510            trim_trailing_whitespace_on_save: Some(cfg.trim_trailing_whitespace_on_save),
511            ensure_final_newline_on_save: Some(cfg.ensure_final_newline_on_save),
512            highlight_matching_brackets: Some(cfg.highlight_matching_brackets),
513            rainbow_brackets: Some(cfg.rainbow_brackets),
514            cursor_style: Some(cfg.cursor_style),
515            keyboard_disambiguate_escape_codes: Some(cfg.keyboard_disambiguate_escape_codes),
516            keyboard_report_event_types: Some(cfg.keyboard_report_event_types),
517            keyboard_report_alternate_keys: Some(cfg.keyboard_report_alternate_keys),
518            keyboard_report_all_keys_as_escape_codes: Some(
519                cfg.keyboard_report_all_keys_as_escape_codes,
520            ),
521            completion_popup_auto_show: Some(cfg.completion_popup_auto_show),
522            quick_suggestions: Some(cfg.quick_suggestions),
523            quick_suggestions_delay_ms: Some(cfg.quick_suggestions_delay_ms),
524            suggest_on_trigger_characters: Some(cfg.suggest_on_trigger_characters),
525            show_menu_bar: Some(cfg.show_menu_bar),
526            menu_bar_mnemonics: Some(cfg.menu_bar_mnemonics),
527            show_tab_bar: Some(cfg.show_tab_bar),
528            show_status_bar: Some(cfg.show_status_bar),
529            show_prompt_line: Some(cfg.show_prompt_line),
530            show_vertical_scrollbar: Some(cfg.show_vertical_scrollbar),
531            show_horizontal_scrollbar: Some(cfg.show_horizontal_scrollbar),
532            show_tilde: Some(cfg.show_tilde),
533            use_terminal_bg: Some(cfg.use_terminal_bg),
534            rulers: Some(cfg.rulers.clone()),
535            whitespace_show: Some(cfg.whitespace_show),
536            whitespace_spaces_leading: Some(cfg.whitespace_spaces_leading),
537            whitespace_spaces_inner: Some(cfg.whitespace_spaces_inner),
538            whitespace_spaces_trailing: Some(cfg.whitespace_spaces_trailing),
539            whitespace_tabs_leading: Some(cfg.whitespace_tabs_leading),
540            whitespace_tabs_inner: Some(cfg.whitespace_tabs_inner),
541            whitespace_tabs_trailing: Some(cfg.whitespace_tabs_trailing),
542        }
543    }
544}
545
546impl PartialEditorConfig {
547    /// Resolve this partial config to a concrete EditorConfig using defaults.
548    pub fn resolve(self, defaults: &crate::config::EditorConfig) -> crate::config::EditorConfig {
549        crate::config::EditorConfig {
550            use_tabs: self.use_tabs.unwrap_or(defaults.use_tabs),
551            tab_size: self.tab_size.unwrap_or(defaults.tab_size),
552            auto_indent: self.auto_indent.unwrap_or(defaults.auto_indent),
553            auto_close: self.auto_close.unwrap_or(defaults.auto_close),
554            auto_surround: self.auto_surround.unwrap_or(defaults.auto_surround),
555            line_numbers: self.line_numbers.unwrap_or(defaults.line_numbers),
556            relative_line_numbers: self
557                .relative_line_numbers
558                .unwrap_or(defaults.relative_line_numbers),
559            scroll_offset: self.scroll_offset.unwrap_or(defaults.scroll_offset),
560            syntax_highlighting: self
561                .syntax_highlighting
562                .unwrap_or(defaults.syntax_highlighting),
563            highlight_current_line: self
564                .highlight_current_line
565                .unwrap_or(defaults.highlight_current_line),
566            line_wrap: self.line_wrap.unwrap_or(defaults.line_wrap),
567            wrap_indent: self.wrap_indent.unwrap_or(defaults.wrap_indent),
568            wrap_column: self.wrap_column.unwrap_or(defaults.wrap_column),
569            page_width: self.page_width.unwrap_or(defaults.page_width),
570            highlight_timeout_ms: self
571                .highlight_timeout_ms
572                .unwrap_or(defaults.highlight_timeout_ms),
573            snapshot_interval: self.snapshot_interval.unwrap_or(defaults.snapshot_interval),
574            large_file_threshold_bytes: self
575                .large_file_threshold_bytes
576                .unwrap_or(defaults.large_file_threshold_bytes),
577            estimated_line_length: self
578                .estimated_line_length
579                .unwrap_or(defaults.estimated_line_length),
580            enable_inlay_hints: self
581                .enable_inlay_hints
582                .unwrap_or(defaults.enable_inlay_hints),
583            enable_semantic_tokens_full: self
584                .enable_semantic_tokens_full
585                .unwrap_or(defaults.enable_semantic_tokens_full),
586            diagnostics_inline_text: self
587                .diagnostics_inline_text
588                .unwrap_or(defaults.diagnostics_inline_text),
589            recovery_enabled: self.recovery_enabled.unwrap_or(defaults.recovery_enabled),
590            auto_recovery_save_interval_secs: self
591                .auto_recovery_save_interval_secs
592                .unwrap_or(defaults.auto_recovery_save_interval_secs),
593            auto_save_enabled: self.auto_save_enabled.unwrap_or(defaults.auto_save_enabled),
594            auto_save_interval_secs: self
595                .auto_save_interval_secs
596                .unwrap_or(defaults.auto_save_interval_secs),
597            hot_exit: self.hot_exit.unwrap_or(defaults.hot_exit),
598            highlight_context_bytes: self
599                .highlight_context_bytes
600                .unwrap_or(defaults.highlight_context_bytes),
601            mouse_hover_enabled: self
602                .mouse_hover_enabled
603                .unwrap_or(defaults.mouse_hover_enabled),
604            mouse_hover_delay_ms: self
605                .mouse_hover_delay_ms
606                .unwrap_or(defaults.mouse_hover_delay_ms),
607            double_click_time_ms: self
608                .double_click_time_ms
609                .unwrap_or(defaults.double_click_time_ms),
610            auto_revert_poll_interval_ms: self
611                .auto_revert_poll_interval_ms
612                .unwrap_or(defaults.auto_revert_poll_interval_ms),
613            read_concurrency: self.read_concurrency.unwrap_or(defaults.read_concurrency),
614            file_tree_poll_interval_ms: self
615                .file_tree_poll_interval_ms
616                .unwrap_or(defaults.file_tree_poll_interval_ms),
617            default_line_ending: self
618                .default_line_ending
619                .unwrap_or(defaults.default_line_ending.clone()),
620            trim_trailing_whitespace_on_save: self
621                .trim_trailing_whitespace_on_save
622                .unwrap_or(defaults.trim_trailing_whitespace_on_save),
623            ensure_final_newline_on_save: self
624                .ensure_final_newline_on_save
625                .unwrap_or(defaults.ensure_final_newline_on_save),
626            highlight_matching_brackets: self
627                .highlight_matching_brackets
628                .unwrap_or(defaults.highlight_matching_brackets),
629            rainbow_brackets: self.rainbow_brackets.unwrap_or(defaults.rainbow_brackets),
630            cursor_style: self.cursor_style.unwrap_or(defaults.cursor_style),
631            keyboard_disambiguate_escape_codes: self
632                .keyboard_disambiguate_escape_codes
633                .unwrap_or(defaults.keyboard_disambiguate_escape_codes),
634            keyboard_report_event_types: self
635                .keyboard_report_event_types
636                .unwrap_or(defaults.keyboard_report_event_types),
637            keyboard_report_alternate_keys: self
638                .keyboard_report_alternate_keys
639                .unwrap_or(defaults.keyboard_report_alternate_keys),
640            keyboard_report_all_keys_as_escape_codes: self
641                .keyboard_report_all_keys_as_escape_codes
642                .unwrap_or(defaults.keyboard_report_all_keys_as_escape_codes),
643            completion_popup_auto_show: self
644                .completion_popup_auto_show
645                .unwrap_or(defaults.completion_popup_auto_show),
646            quick_suggestions: self.quick_suggestions.unwrap_or(defaults.quick_suggestions),
647            quick_suggestions_delay_ms: self
648                .quick_suggestions_delay_ms
649                .unwrap_or(defaults.quick_suggestions_delay_ms),
650            suggest_on_trigger_characters: self
651                .suggest_on_trigger_characters
652                .unwrap_or(defaults.suggest_on_trigger_characters),
653            show_menu_bar: self.show_menu_bar.unwrap_or(defaults.show_menu_bar),
654            menu_bar_mnemonics: self
655                .menu_bar_mnemonics
656                .unwrap_or(defaults.menu_bar_mnemonics),
657            show_tab_bar: self.show_tab_bar.unwrap_or(defaults.show_tab_bar),
658            show_status_bar: self.show_status_bar.unwrap_or(defaults.show_status_bar),
659            show_prompt_line: self.show_prompt_line.unwrap_or(defaults.show_prompt_line),
660            show_vertical_scrollbar: self
661                .show_vertical_scrollbar
662                .unwrap_or(defaults.show_vertical_scrollbar),
663            show_horizontal_scrollbar: self
664                .show_horizontal_scrollbar
665                .unwrap_or(defaults.show_horizontal_scrollbar),
666            show_tilde: self.show_tilde.unwrap_or(defaults.show_tilde),
667            use_terminal_bg: self.use_terminal_bg.unwrap_or(defaults.use_terminal_bg),
668            rulers: self.rulers.unwrap_or_else(|| defaults.rulers.clone()),
669            whitespace_show: self.whitespace_show.unwrap_or(defaults.whitespace_show),
670            whitespace_spaces_leading: self
671                .whitespace_spaces_leading
672                .unwrap_or(defaults.whitespace_spaces_leading),
673            whitespace_spaces_inner: self
674                .whitespace_spaces_inner
675                .unwrap_or(defaults.whitespace_spaces_inner),
676            whitespace_spaces_trailing: self
677                .whitespace_spaces_trailing
678                .unwrap_or(defaults.whitespace_spaces_trailing),
679            whitespace_tabs_leading: self
680                .whitespace_tabs_leading
681                .unwrap_or(defaults.whitespace_tabs_leading),
682            whitespace_tabs_inner: self
683                .whitespace_tabs_inner
684                .unwrap_or(defaults.whitespace_tabs_inner),
685            whitespace_tabs_trailing: self
686                .whitespace_tabs_trailing
687                .unwrap_or(defaults.whitespace_tabs_trailing),
688        }
689    }
690}
691
692impl From<&FileExplorerConfig> for PartialFileExplorerConfig {
693    fn from(cfg: &FileExplorerConfig) -> Self {
694        Self {
695            respect_gitignore: Some(cfg.respect_gitignore),
696            show_hidden: Some(cfg.show_hidden),
697            show_gitignored: Some(cfg.show_gitignored),
698            custom_ignore_patterns: Some(cfg.custom_ignore_patterns.clone()),
699            width: Some(cfg.width),
700        }
701    }
702}
703
704impl PartialFileExplorerConfig {
705    pub fn resolve(self, defaults: &FileExplorerConfig) -> FileExplorerConfig {
706        FileExplorerConfig {
707            respect_gitignore: self.respect_gitignore.unwrap_or(defaults.respect_gitignore),
708            show_hidden: self.show_hidden.unwrap_or(defaults.show_hidden),
709            show_gitignored: self.show_gitignored.unwrap_or(defaults.show_gitignored),
710            custom_ignore_patterns: self
711                .custom_ignore_patterns
712                .unwrap_or_else(|| defaults.custom_ignore_patterns.clone()),
713            width: self.width.unwrap_or(defaults.width),
714        }
715    }
716}
717
718impl From<&FileBrowserConfig> for PartialFileBrowserConfig {
719    fn from(cfg: &FileBrowserConfig) -> Self {
720        Self {
721            show_hidden: Some(cfg.show_hidden),
722        }
723    }
724}
725
726impl PartialFileBrowserConfig {
727    pub fn resolve(self, defaults: &FileBrowserConfig) -> FileBrowserConfig {
728        FileBrowserConfig {
729            show_hidden: self.show_hidden.unwrap_or(defaults.show_hidden),
730        }
731    }
732}
733
734impl From<&ClipboardConfig> for PartialClipboardConfig {
735    fn from(cfg: &ClipboardConfig) -> Self {
736        Self {
737            use_osc52: Some(cfg.use_osc52),
738            use_system_clipboard: Some(cfg.use_system_clipboard),
739        }
740    }
741}
742
743impl PartialClipboardConfig {
744    pub fn resolve(self, defaults: &ClipboardConfig) -> ClipboardConfig {
745        ClipboardConfig {
746            use_osc52: self.use_osc52.unwrap_or(defaults.use_osc52),
747            use_system_clipboard: self
748                .use_system_clipboard
749                .unwrap_or(defaults.use_system_clipboard),
750        }
751    }
752}
753
754impl From<&TerminalConfig> for PartialTerminalConfig {
755    fn from(cfg: &TerminalConfig) -> Self {
756        Self {
757            jump_to_end_on_output: Some(cfg.jump_to_end_on_output),
758        }
759    }
760}
761
762impl PartialTerminalConfig {
763    pub fn resolve(self, defaults: &TerminalConfig) -> TerminalConfig {
764        TerminalConfig {
765            jump_to_end_on_output: self
766                .jump_to_end_on_output
767                .unwrap_or(defaults.jump_to_end_on_output),
768        }
769    }
770}
771
772impl From<&WarningsConfig> for PartialWarningsConfig {
773    fn from(cfg: &WarningsConfig) -> Self {
774        Self {
775            show_status_indicator: Some(cfg.show_status_indicator),
776        }
777    }
778}
779
780impl PartialWarningsConfig {
781    pub fn resolve(self, defaults: &WarningsConfig) -> WarningsConfig {
782        WarningsConfig {
783            show_status_indicator: self
784                .show_status_indicator
785                .unwrap_or(defaults.show_status_indicator),
786        }
787    }
788}
789
790impl From<&crate::config::PackagesConfig> for PartialPackagesConfig {
791    fn from(cfg: &crate::config::PackagesConfig) -> Self {
792        Self {
793            sources: Some(cfg.sources.clone()),
794        }
795    }
796}
797
798impl PartialPackagesConfig {
799    pub fn resolve(
800        self,
801        defaults: &crate::config::PackagesConfig,
802    ) -> crate::config::PackagesConfig {
803        crate::config::PackagesConfig {
804            sources: self.sources.unwrap_or_else(|| defaults.sources.clone()),
805        }
806    }
807}
808
809impl From<&PluginConfig> for PartialPluginConfig {
810    fn from(cfg: &PluginConfig) -> Self {
811        Self {
812            enabled: Some(cfg.enabled),
813            path: cfg.path.clone(),
814        }
815    }
816}
817
818impl PartialPluginConfig {
819    pub fn resolve(self, defaults: &PluginConfig) -> PluginConfig {
820        PluginConfig {
821            enabled: self.enabled.unwrap_or(defaults.enabled),
822            path: self.path.or_else(|| defaults.path.clone()),
823        }
824    }
825}
826
827impl From<&LanguageConfig> for PartialLanguageConfig {
828    fn from(cfg: &LanguageConfig) -> Self {
829        Self {
830            extensions: Some(cfg.extensions.clone()),
831            filenames: Some(cfg.filenames.clone()),
832            grammar: Some(cfg.grammar.clone()),
833            comment_prefix: cfg.comment_prefix.clone(),
834            auto_indent: Some(cfg.auto_indent),
835            auto_close: cfg.auto_close,
836            auto_surround: cfg.auto_surround,
837            highlighter: Some(cfg.highlighter),
838            textmate_grammar: cfg.textmate_grammar.clone(),
839            show_whitespace_tabs: Some(cfg.show_whitespace_tabs),
840            line_wrap: cfg.line_wrap,
841            wrap_column: Some(cfg.wrap_column),
842            page_view: cfg.page_view,
843            page_width: Some(cfg.page_width),
844            use_tabs: cfg.use_tabs,
845            tab_size: cfg.tab_size,
846            formatter: cfg.formatter.clone(),
847            format_on_save: Some(cfg.format_on_save),
848            on_save: Some(cfg.on_save.clone()),
849            word_characters: Some(cfg.word_characters.clone()),
850        }
851    }
852}
853
854impl PartialLanguageConfig {
855    pub fn resolve(self, defaults: &LanguageConfig) -> LanguageConfig {
856        LanguageConfig {
857            extensions: self
858                .extensions
859                .unwrap_or_else(|| defaults.extensions.clone()),
860            filenames: self.filenames.unwrap_or_else(|| defaults.filenames.clone()),
861            grammar: self.grammar.unwrap_or_else(|| defaults.grammar.clone()),
862            comment_prefix: self
863                .comment_prefix
864                .or_else(|| defaults.comment_prefix.clone()),
865            auto_indent: self.auto_indent.unwrap_or(defaults.auto_indent),
866            auto_close: self.auto_close.or(defaults.auto_close),
867            auto_surround: self.auto_surround.or(defaults.auto_surround),
868            highlighter: self.highlighter.unwrap_or(defaults.highlighter),
869            textmate_grammar: self
870                .textmate_grammar
871                .or_else(|| defaults.textmate_grammar.clone()),
872            show_whitespace_tabs: self
873                .show_whitespace_tabs
874                .unwrap_or(defaults.show_whitespace_tabs),
875            line_wrap: self.line_wrap.or(defaults.line_wrap),
876            wrap_column: self.wrap_column.unwrap_or(defaults.wrap_column),
877            page_view: self.page_view.or(defaults.page_view),
878            page_width: self.page_width.unwrap_or(defaults.page_width),
879            use_tabs: self.use_tabs.or(defaults.use_tabs),
880            tab_size: self.tab_size.or(defaults.tab_size),
881            formatter: self.formatter.or_else(|| defaults.formatter.clone()),
882            format_on_save: self.format_on_save.unwrap_or(defaults.format_on_save),
883            on_save: self.on_save.unwrap_or_else(|| defaults.on_save.clone()),
884            word_characters: self
885                .word_characters
886                .unwrap_or_else(|| defaults.word_characters.clone()),
887        }
888    }
889}
890
891impl From<&crate::config::Config> for PartialConfig {
892    fn from(cfg: &crate::config::Config) -> Self {
893        Self {
894            version: Some(cfg.version),
895            theme: Some(cfg.theme.clone()),
896            locale: cfg.locale.0.clone(),
897            check_for_updates: Some(cfg.check_for_updates),
898            editor: Some(PartialEditorConfig::from(&cfg.editor)),
899            file_explorer: Some(PartialFileExplorerConfig::from(&cfg.file_explorer)),
900            file_browser: Some(PartialFileBrowserConfig::from(&cfg.file_browser)),
901            clipboard: Some(PartialClipboardConfig::from(&cfg.clipboard)),
902            terminal: Some(PartialTerminalConfig::from(&cfg.terminal)),
903            keybindings: Some(cfg.keybindings.clone()),
904            keybinding_maps: Some(cfg.keybinding_maps.clone()),
905            active_keybinding_map: Some(cfg.active_keybinding_map.clone()),
906            languages: Some(
907                cfg.languages
908                    .iter()
909                    .map(|(k, v)| (k.clone(), PartialLanguageConfig::from(v)))
910                    .collect(),
911            ),
912            fallback: cfg.fallback.clone(),
913            lsp: Some(
914                cfg.lsp
915                    .iter()
916                    .map(|(k, v)| {
917                        // Normalize to Single for 1-element arrays so that
918                        // json_diff can compare object fields recursively
919                        // (arrays are compared wholesale, not element-wise).
920                        let lang_config = match v {
921                            LspLanguageConfig::Multi(vec) if vec.len() == 1 => {
922                                LspLanguageConfig::Single(Box::new(vec[0].clone()))
923                            }
924                            other => other.clone(),
925                        };
926                        (k.clone(), lang_config)
927                    })
928                    .collect(),
929            ),
930            warnings: Some(PartialWarningsConfig::from(&cfg.warnings)),
931            // Only include plugins that differ from defaults
932            // Path is auto-discovered at runtime and should never be saved
933            plugins: {
934                let default_plugin = crate::config::PluginConfig::default();
935                let non_default_plugins: HashMap<String, PartialPluginConfig> = cfg
936                    .plugins
937                    .iter()
938                    .filter(|(_, v)| v.enabled != default_plugin.enabled)
939                    .map(|(k, v)| {
940                        (
941                            k.clone(),
942                            PartialPluginConfig {
943                                enabled: Some(v.enabled),
944                                path: None, // Don't save path - it's auto-discovered
945                            },
946                        )
947                    })
948                    .collect();
949                if non_default_plugins.is_empty() {
950                    None
951                } else {
952                    Some(non_default_plugins)
953                }
954            },
955            packages: Some(PartialPackagesConfig::from(&cfg.packages)),
956        }
957    }
958}
959
960impl PartialConfig {
961    /// Resolve this partial config to a concrete Config using system defaults.
962    pub fn resolve(self) -> crate::config::Config {
963        let defaults = crate::config::Config::default();
964        self.resolve_with_defaults(&defaults)
965    }
966
967    /// Resolve this partial config to a concrete Config using provided defaults.
968    pub fn resolve_with_defaults(self, defaults: &crate::config::Config) -> crate::config::Config {
969        // Resolve languages HashMap - merge with defaults
970        let languages = {
971            let mut result = defaults.languages.clone();
972            if let Some(partial_langs) = self.languages {
973                for (key, partial_lang) in partial_langs {
974                    let default_lang = result.get(&key).cloned().unwrap_or_default();
975                    result.insert(key, partial_lang.resolve(&default_lang));
976                }
977            }
978            result
979        };
980
981        // Resolve lsp HashMap - merge with defaults
982        // Each language can have one or more server configs.
983        // User config (LspLanguageConfig) can be a single object or an array.
984        let lsp = {
985            let mut result = defaults.lsp.clone();
986            if let Some(partial_lsp) = self.lsp {
987                for (key, lang_config) in partial_lsp {
988                    let user_configs = lang_config.into_vec();
989                    if let Some(default_configs) = result.get(&key) {
990                        let default_slice = default_configs.as_slice();
991                        // For single-server user config, merge with the first default.
992                        // For multi-server user config, replace entirely (user is
993                        // explicitly configuring the full server list).
994                        if user_configs.len() == 1 && default_slice.len() == 1 {
995                            let merged = user_configs
996                                .into_iter()
997                                .next()
998                                .unwrap()
999                                .merge_with_defaults(&default_slice[0]);
1000                            result.insert(key, LspLanguageConfig::Multi(vec![merged]));
1001                        } else {
1002                            result.insert(key, LspLanguageConfig::Multi(user_configs));
1003                        }
1004                    } else {
1005                        // New language not in defaults - use as-is
1006                        result.insert(key, LspLanguageConfig::Multi(user_configs));
1007                    }
1008                }
1009            }
1010            result
1011        };
1012
1013        // Resolve keybinding_maps HashMap - merge with defaults
1014        let keybinding_maps = {
1015            let mut result = defaults.keybinding_maps.clone();
1016            if let Some(partial_maps) = self.keybinding_maps {
1017                for (key, config) in partial_maps {
1018                    result.insert(key, config);
1019                }
1020            }
1021            result
1022        };
1023
1024        // Resolve plugins HashMap - merge with defaults
1025        let plugins = {
1026            let mut result = defaults.plugins.clone();
1027            if let Some(partial_plugins) = self.plugins {
1028                for (key, partial_plugin) in partial_plugins {
1029                    let default_plugin = result.get(&key).cloned().unwrap_or_default();
1030                    result.insert(key, partial_plugin.resolve(&default_plugin));
1031                }
1032            }
1033            result
1034        };
1035
1036        crate::config::Config {
1037            version: self.version.unwrap_or(defaults.version),
1038            theme: self.theme.unwrap_or_else(|| defaults.theme.clone()),
1039            locale: crate::config::LocaleName::from(
1040                self.locale.or_else(|| defaults.locale.0.clone()),
1041            ),
1042            check_for_updates: self.check_for_updates.unwrap_or(defaults.check_for_updates),
1043            editor: self
1044                .editor
1045                .map(|e| e.resolve(&defaults.editor))
1046                .unwrap_or_else(|| defaults.editor.clone()),
1047            file_explorer: self
1048                .file_explorer
1049                .map(|e| e.resolve(&defaults.file_explorer))
1050                .unwrap_or_else(|| defaults.file_explorer.clone()),
1051            file_browser: self
1052                .file_browser
1053                .map(|e| e.resolve(&defaults.file_browser))
1054                .unwrap_or_else(|| defaults.file_browser.clone()),
1055            clipboard: self
1056                .clipboard
1057                .map(|e| e.resolve(&defaults.clipboard))
1058                .unwrap_or_else(|| defaults.clipboard.clone()),
1059            terminal: self
1060                .terminal
1061                .map(|e| e.resolve(&defaults.terminal))
1062                .unwrap_or_else(|| defaults.terminal.clone()),
1063            keybindings: self
1064                .keybindings
1065                .unwrap_or_else(|| defaults.keybindings.clone()),
1066            keybinding_maps,
1067            active_keybinding_map: self
1068                .active_keybinding_map
1069                .unwrap_or_else(|| defaults.active_keybinding_map.clone()),
1070            languages,
1071            fallback: self.fallback.or_else(|| defaults.fallback.clone()),
1072            lsp,
1073            warnings: self
1074                .warnings
1075                .map(|e| e.resolve(&defaults.warnings))
1076                .unwrap_or_else(|| defaults.warnings.clone()),
1077            plugins,
1078            packages: self
1079                .packages
1080                .map(|e| e.resolve(&defaults.packages))
1081                .unwrap_or_else(|| defaults.packages.clone()),
1082        }
1083    }
1084}
1085
1086// Default implementation for LanguageConfig to support merge_hashmap_recursive
1087impl Default for LanguageConfig {
1088    fn default() -> Self {
1089        Self {
1090            extensions: Vec::new(),
1091            filenames: Vec::new(),
1092            grammar: String::new(),
1093            comment_prefix: None,
1094            auto_indent: true,
1095            auto_close: None,
1096            auto_surround: None,
1097            highlighter: HighlighterPreference::default(),
1098            textmate_grammar: None,
1099            show_whitespace_tabs: true,
1100            line_wrap: None,
1101            wrap_column: None,
1102            page_view: None,
1103            page_width: None,
1104            use_tabs: None,
1105            tab_size: None,
1106            formatter: None,
1107            format_on_save: false,
1108            on_save: Vec::new(),
1109            word_characters: None,
1110        }
1111    }
1112}
1113
1114/// Session-specific configuration for runtime/volatile overrides.
1115///
1116/// This struct represents the session layer of the config hierarchy - settings
1117/// that are temporary and may not persist across editor restarts.
1118///
1119/// Unlike PartialConfig, SessionConfig provides a focused API for common
1120/// runtime modifications like temporary theme switching.
1121#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1122#[serde(default)]
1123pub struct SessionConfig {
1124    /// Temporarily override the theme (e.g., for preview)
1125    pub theme: Option<ThemeName>,
1126
1127    /// Temporary editor overrides (e.g., changing tab_size for current session)
1128    pub editor: Option<PartialEditorConfig>,
1129
1130    /// Buffer-specific overrides keyed by absolute file path.
1131    /// These allow per-file settings that persist only during the session.
1132    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
1133    pub buffer_overrides: HashMap<std::path::PathBuf, PartialEditorConfig>,
1134}
1135
1136impl SessionConfig {
1137    /// Create a new empty session config.
1138    pub fn new() -> Self {
1139        Self::default()
1140    }
1141
1142    /// Set a temporary theme override.
1143    pub fn set_theme(&mut self, theme: ThemeName) {
1144        self.theme = Some(theme);
1145    }
1146
1147    /// Clear the theme override, reverting to lower layers.
1148    pub fn clear_theme(&mut self) {
1149        self.theme = None;
1150    }
1151
1152    /// Set an editor setting for the current session.
1153    pub fn set_editor_option<F>(&mut self, setter: F)
1154    where
1155        F: FnOnce(&mut PartialEditorConfig),
1156    {
1157        let editor = self.editor.get_or_insert_with(Default::default);
1158        setter(editor);
1159    }
1160
1161    /// Set a buffer-specific editor override.
1162    pub fn set_buffer_override(&mut self, path: std::path::PathBuf, config: PartialEditorConfig) {
1163        self.buffer_overrides.insert(path, config);
1164    }
1165
1166    /// Clear buffer-specific overrides for a path.
1167    pub fn clear_buffer_override(&mut self, path: &std::path::Path) {
1168        self.buffer_overrides.remove(path);
1169    }
1170
1171    /// Get buffer-specific editor config if set.
1172    pub fn get_buffer_override(&self, path: &std::path::Path) -> Option<&PartialEditorConfig> {
1173        self.buffer_overrides.get(path)
1174    }
1175
1176    /// Convert to a PartialConfig for merging with other layers.
1177    pub fn to_partial_config(&self) -> PartialConfig {
1178        PartialConfig {
1179            theme: self.theme.clone(),
1180            editor: self.editor.clone(),
1181            ..Default::default()
1182        }
1183    }
1184
1185    /// Check if this session config has any values set.
1186    pub fn is_empty(&self) -> bool {
1187        self.theme.is_none() && self.editor.is_none() && self.buffer_overrides.is_empty()
1188    }
1189}
1190
1191impl From<PartialConfig> for SessionConfig {
1192    fn from(partial: PartialConfig) -> Self {
1193        Self {
1194            theme: partial.theme,
1195            editor: partial.editor,
1196            buffer_overrides: HashMap::new(),
1197        }
1198    }
1199}
1200
1201#[cfg(test)]
1202mod tests {
1203    use super::*;
1204
1205    #[test]
1206    fn merge_option_higher_precedence_wins() {
1207        let mut higher: Option<i32> = Some(10);
1208        let lower: Option<i32> = Some(5);
1209        higher.merge_from(&lower);
1210        assert_eq!(higher, Some(10));
1211    }
1212
1213    #[test]
1214    fn merge_option_fills_from_lower_when_none() {
1215        let mut higher: Option<i32> = None;
1216        let lower: Option<i32> = Some(5);
1217        higher.merge_from(&lower);
1218        assert_eq!(higher, Some(5));
1219    }
1220
1221    #[test]
1222    fn merge_editor_config_recursive() {
1223        let mut higher = PartialEditorConfig {
1224            tab_size: Some(2),
1225            ..Default::default()
1226        };
1227        let lower = PartialEditorConfig {
1228            tab_size: Some(4),
1229            line_numbers: Some(true),
1230            ..Default::default()
1231        };
1232
1233        higher.merge_from(&lower);
1234
1235        assert_eq!(higher.tab_size, Some(2)); // Higher wins
1236        assert_eq!(higher.line_numbers, Some(true)); // Filled from lower
1237    }
1238
1239    #[test]
1240    fn merge_partial_config_combines_languages() {
1241        let mut higher = PartialConfig {
1242            languages: Some(HashMap::from([(
1243                "rust".to_string(),
1244                PartialLanguageConfig {
1245                    tab_size: Some(4),
1246                    ..Default::default()
1247                },
1248            )])),
1249            ..Default::default()
1250        };
1251        let lower = PartialConfig {
1252            languages: Some(HashMap::from([(
1253                "python".to_string(),
1254                PartialLanguageConfig {
1255                    tab_size: Some(4),
1256                    ..Default::default()
1257                },
1258            )])),
1259            ..Default::default()
1260        };
1261
1262        higher.merge_from(&lower);
1263
1264        let langs = higher.languages.unwrap();
1265        assert!(langs.contains_key("rust"));
1266        assert!(langs.contains_key("python"));
1267    }
1268
1269    #[test]
1270    fn merge_languages_same_key_higher_wins() {
1271        let mut higher = PartialConfig {
1272            languages: Some(HashMap::from([(
1273                "rust".to_string(),
1274                PartialLanguageConfig {
1275                    tab_size: Some(2),
1276                    use_tabs: Some(true),
1277                    ..Default::default()
1278                },
1279            )])),
1280            ..Default::default()
1281        };
1282        let lower = PartialConfig {
1283            languages: Some(HashMap::from([(
1284                "rust".to_string(),
1285                PartialLanguageConfig {
1286                    tab_size: Some(4),
1287                    auto_indent: Some(false),
1288                    ..Default::default()
1289                },
1290            )])),
1291            ..Default::default()
1292        };
1293
1294        higher.merge_from(&lower);
1295
1296        let langs = higher.languages.unwrap();
1297        let rust = langs.get("rust").unwrap();
1298        assert_eq!(rust.tab_size, Some(2)); // Higher wins
1299        assert_eq!(rust.use_tabs, Some(true)); // From higher
1300        assert_eq!(rust.auto_indent, Some(false)); // Filled from lower
1301    }
1302
1303    #[test]
1304    fn resolve_fills_defaults() {
1305        let partial = PartialConfig {
1306            theme: Some(ThemeName::from("dark")),
1307            ..Default::default()
1308        };
1309
1310        let resolved = partial.resolve();
1311
1312        assert_eq!(resolved.theme.0, "dark");
1313        assert_eq!(resolved.editor.tab_size, 4); // Default
1314        assert!(resolved.editor.line_numbers); // Default true
1315    }
1316
1317    #[test]
1318    fn resolve_preserves_set_values() {
1319        let partial = PartialConfig {
1320            editor: Some(PartialEditorConfig {
1321                tab_size: Some(2),
1322                line_numbers: Some(false),
1323                ..Default::default()
1324            }),
1325            ..Default::default()
1326        };
1327
1328        let resolved = partial.resolve();
1329
1330        assert_eq!(resolved.editor.tab_size, 2);
1331        assert!(!resolved.editor.line_numbers);
1332    }
1333
1334    #[test]
1335    fn roundtrip_config_to_partial_and_back() {
1336        let original = crate::config::Config::default();
1337        let partial = PartialConfig::from(&original);
1338        let resolved = partial.resolve();
1339
1340        assert_eq!(original.theme, resolved.theme);
1341        assert_eq!(original.editor.tab_size, resolved.editor.tab_size);
1342        assert_eq!(original.check_for_updates, resolved.check_for_updates);
1343    }
1344
1345    #[test]
1346    fn session_config_new_is_empty() {
1347        let session = SessionConfig::new();
1348        assert!(session.is_empty());
1349    }
1350
1351    #[test]
1352    fn session_config_set_theme() {
1353        let mut session = SessionConfig::new();
1354        session.set_theme(ThemeName::from("dark"));
1355        assert_eq!(session.theme, Some(ThemeName::from("dark")));
1356        assert!(!session.is_empty());
1357    }
1358
1359    #[test]
1360    fn session_config_clear_theme() {
1361        let mut session = SessionConfig::new();
1362        session.set_theme(ThemeName::from("dark"));
1363        session.clear_theme();
1364        assert!(session.theme.is_none());
1365    }
1366
1367    #[test]
1368    fn session_config_set_editor_option() {
1369        let mut session = SessionConfig::new();
1370        session.set_editor_option(|e| e.tab_size = Some(2));
1371        assert_eq!(session.editor.as_ref().unwrap().tab_size, Some(2));
1372    }
1373
1374    #[test]
1375    fn session_config_buffer_overrides() {
1376        let mut session = SessionConfig::new();
1377        let path = std::path::PathBuf::from("/test/file.rs");
1378        let config = PartialEditorConfig {
1379            tab_size: Some(8),
1380            ..Default::default()
1381        };
1382
1383        session.set_buffer_override(path.clone(), config);
1384        assert!(session.get_buffer_override(&path).is_some());
1385        assert_eq!(
1386            session.get_buffer_override(&path).unwrap().tab_size,
1387            Some(8)
1388        );
1389
1390        session.clear_buffer_override(&path);
1391        assert!(session.get_buffer_override(&path).is_none());
1392    }
1393
1394    #[test]
1395    fn session_config_to_partial_config() {
1396        let mut session = SessionConfig::new();
1397        session.set_theme(ThemeName::from("dark"));
1398        session.set_editor_option(|e| e.tab_size = Some(2));
1399
1400        let partial = session.to_partial_config();
1401        assert_eq!(partial.theme, Some(ThemeName::from("dark")));
1402        assert_eq!(partial.editor.as_ref().unwrap().tab_size, Some(2));
1403    }
1404
1405    // ============= Plugin Config Delta Saving Tests =============
1406
1407    #[test]
1408    fn plugins_with_default_enabled_not_serialized() {
1409        // When all plugins have enabled=true (the default), plugins should be None
1410        let mut config = crate::config::Config::default();
1411        config.plugins.insert(
1412            "test_plugin".to_string(),
1413            PluginConfig {
1414                enabled: true, // Default value
1415                path: Some(std::path::PathBuf::from("/path/to/plugin.ts")),
1416            },
1417        );
1418
1419        let partial = PartialConfig::from(&config);
1420
1421        // plugins should be None since all have default values
1422        assert!(
1423            partial.plugins.is_none(),
1424            "Plugins with default enabled=true should not be serialized"
1425        );
1426    }
1427
1428    #[test]
1429    fn plugins_with_disabled_are_serialized() {
1430        // When a plugin is disabled, it should be included in the partial config
1431        let mut config = crate::config::Config::default();
1432        config.plugins.insert(
1433            "enabled_plugin".to_string(),
1434            PluginConfig {
1435                enabled: true,
1436                path: Some(std::path::PathBuf::from("/path/to/enabled.ts")),
1437            },
1438        );
1439        config.plugins.insert(
1440            "disabled_plugin".to_string(),
1441            PluginConfig {
1442                enabled: false, // Not default!
1443                path: Some(std::path::PathBuf::from("/path/to/disabled.ts")),
1444            },
1445        );
1446
1447        let partial = PartialConfig::from(&config);
1448
1449        // plugins should contain only the disabled plugin
1450        assert!(partial.plugins.is_some());
1451        let plugins = partial.plugins.unwrap();
1452        assert_eq!(
1453            plugins.len(),
1454            1,
1455            "Only disabled plugins should be serialized"
1456        );
1457        assert!(plugins.contains_key("disabled_plugin"));
1458        assert!(!plugins.contains_key("enabled_plugin"));
1459
1460        // Check the disabled plugin has correct values
1461        let disabled = plugins.get("disabled_plugin").unwrap();
1462        assert_eq!(disabled.enabled, Some(false));
1463        // Path should be None - it's auto-discovered and shouldn't be saved
1464        assert!(disabled.path.is_none(), "Path should not be serialized");
1465    }
1466
1467    #[test]
1468    fn plugin_path_never_serialized() {
1469        // Even for disabled plugins, path should never be serialized
1470        let mut config = crate::config::Config::default();
1471        config.plugins.insert(
1472            "my_plugin".to_string(),
1473            PluginConfig {
1474                enabled: false,
1475                path: Some(std::path::PathBuf::from("/some/path/plugin.ts")),
1476            },
1477        );
1478
1479        let partial = PartialConfig::from(&config);
1480        let plugins = partial.plugins.unwrap();
1481        let plugin = plugins.get("my_plugin").unwrap();
1482
1483        assert!(
1484            plugin.path.is_none(),
1485            "Path is runtime-discovered and should never be serialized"
1486        );
1487    }
1488
1489    #[test]
1490    fn resolving_partial_with_disabled_plugin_preserves_state() {
1491        // Loading a config with a disabled plugin should preserve disabled state
1492        let partial = PartialConfig {
1493            plugins: Some(HashMap::from([(
1494                "my_plugin".to_string(),
1495                PartialPluginConfig {
1496                    enabled: Some(false),
1497                    path: None,
1498                },
1499            )])),
1500            ..Default::default()
1501        };
1502
1503        let resolved = partial.resolve();
1504
1505        // Plugin should exist and be disabled
1506        let plugin = resolved.plugins.get("my_plugin");
1507        assert!(
1508            plugin.is_some(),
1509            "Disabled plugin should be in resolved config"
1510        );
1511        assert!(
1512            !plugin.unwrap().enabled,
1513            "Plugin should remain disabled after resolve"
1514        );
1515    }
1516
1517    #[test]
1518    fn merge_plugins_preserves_higher_precedence_disabled_state() {
1519        // When merging, higher precedence disabled state should win
1520        let mut higher = PartialConfig {
1521            plugins: Some(HashMap::from([(
1522                "my_plugin".to_string(),
1523                PartialPluginConfig {
1524                    enabled: Some(false), // User disabled
1525                    path: None,
1526                },
1527            )])),
1528            ..Default::default()
1529        };
1530
1531        let lower = PartialConfig {
1532            plugins: Some(HashMap::from([(
1533                "my_plugin".to_string(),
1534                PartialPluginConfig {
1535                    enabled: Some(true), // Lower layer has it enabled
1536                    path: None,
1537                },
1538            )])),
1539            ..Default::default()
1540        };
1541
1542        higher.merge_from(&lower);
1543
1544        let plugins = higher.plugins.unwrap();
1545        let plugin = plugins.get("my_plugin").unwrap();
1546        assert_eq!(
1547            plugin.enabled,
1548            Some(false),
1549            "Higher precedence disabled state should win"
1550        );
1551    }
1552
1553    #[test]
1554    fn roundtrip_disabled_plugin_only_saves_delta() {
1555        // Roundtrip test: create config with mix of enabled/disabled plugins,
1556        // convert to partial, serialize to JSON, deserialize, and verify
1557        let mut config = crate::config::Config::default();
1558        config.plugins.insert(
1559            "plugin_a".to_string(),
1560            PluginConfig {
1561                enabled: true,
1562                path: Some(std::path::PathBuf::from("/a.ts")),
1563            },
1564        );
1565        config.plugins.insert(
1566            "plugin_b".to_string(),
1567            PluginConfig {
1568                enabled: false,
1569                path: Some(std::path::PathBuf::from("/b.ts")),
1570            },
1571        );
1572        config.plugins.insert(
1573            "plugin_c".to_string(),
1574            PluginConfig {
1575                enabled: true,
1576                path: Some(std::path::PathBuf::from("/c.ts")),
1577            },
1578        );
1579
1580        // Convert to partial (delta)
1581        let partial = PartialConfig::from(&config);
1582
1583        // Serialize to JSON
1584        let json = serde_json::to_string(&partial).unwrap();
1585
1586        // Verify only plugin_b is in the JSON
1587        assert!(
1588            json.contains("plugin_b"),
1589            "Disabled plugin should be in serialized JSON"
1590        );
1591        assert!(
1592            !json.contains("plugin_a"),
1593            "Enabled plugin_a should not be in serialized JSON"
1594        );
1595        assert!(
1596            !json.contains("plugin_c"),
1597            "Enabled plugin_c should not be in serialized JSON"
1598        );
1599
1600        // Deserialize back
1601        let deserialized: PartialConfig = serde_json::from_str(&json).unwrap();
1602
1603        // Verify plugins section only contains the disabled one
1604        let plugins = deserialized.plugins.unwrap();
1605        assert_eq!(plugins.len(), 1);
1606        assert!(plugins.contains_key("plugin_b"));
1607        assert_eq!(plugins.get("plugin_b").unwrap().enabled, Some(false));
1608    }
1609}