language_settings.rs

  1//! Provides `language`-related settings.
  2
  3use crate::{File, Language, LanguageName, LanguageServerName};
  4use collections::{FxHashMap, HashMap, HashSet};
  5use ec4rs::{
  6    Properties as EditorconfigProperties,
  7    property::{FinalNewline, IndentSize, IndentStyle, MaxLineLen, TabWidth, TrimTrailingWs},
  8};
  9use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
 10use gpui::{App, Modifiers, SharedString};
 11use itertools::{Either, Itertools};
 12use settings::IntoGpui;
 13
 14pub use settings::{
 15    CompletionSettingsContent, EditPredictionProvider, EditPredictionsMode, FormatOnSave,
 16    Formatter, FormatterList, InlayHintKind, LanguageSettingsContent, LspInsertMode,
 17    RewrapBehavior, ShowWhitespaceSetting, SoftWrap, WordsCompletionMode,
 18};
 19use settings::{RegisterSetting, Settings, SettingsLocation, SettingsStore};
 20use shellexpand;
 21use std::{borrow::Cow, num::NonZeroU32, path::Path, sync::Arc};
 22
 23/// Returns the settings for the specified language from the provided file.
 24pub fn language_settings<'a>(
 25    language: Option<LanguageName>,
 26    file: Option<&'a Arc<dyn File>>,
 27    cx: &'a App,
 28) -> Cow<'a, LanguageSettings> {
 29    let location = file.map(|f| SettingsLocation {
 30        worktree_id: f.worktree_id(cx),
 31        path: f.path().as_ref(),
 32    });
 33    AllLanguageSettings::get(location, cx).language(location, language.as_ref(), cx)
 34}
 35
 36/// Returns the settings for all languages from the provided file.
 37pub fn all_language_settings<'a>(
 38    file: Option<&'a Arc<dyn File>>,
 39    cx: &'a App,
 40) -> &'a AllLanguageSettings {
 41    let location = file.map(|f| SettingsLocation {
 42        worktree_id: f.worktree_id(cx),
 43        path: f.path().as_ref(),
 44    });
 45    AllLanguageSettings::get(location, cx)
 46}
 47
 48/// The settings for all languages.
 49#[derive(Debug, Clone, RegisterSetting)]
 50pub struct AllLanguageSettings {
 51    /// The edit prediction settings.
 52    pub edit_predictions: EditPredictionSettings,
 53    pub defaults: LanguageSettings,
 54    languages: HashMap<LanguageName, LanguageSettings>,
 55    pub file_types: FxHashMap<Arc<str>, (GlobSet, Vec<String>)>,
 56}
 57
 58#[derive(Debug, Clone, PartialEq)]
 59pub struct WhitespaceMap {
 60    pub space: SharedString,
 61    pub tab: SharedString,
 62}
 63
 64/// The settings for a particular language.
 65#[derive(Debug, Clone, PartialEq)]
 66pub struct LanguageSettings {
 67    /// How many columns a tab should occupy.
 68    pub tab_size: NonZeroU32,
 69    /// Whether to indent lines using tab characters, as opposed to multiple
 70    /// spaces.
 71    pub hard_tabs: bool,
 72    /// How to soft-wrap long lines of text.
 73    pub soft_wrap: settings::SoftWrap,
 74    /// The column at which to soft-wrap lines, for buffers where soft-wrap
 75    /// is enabled.
 76    pub preferred_line_length: u32,
 77    /// Whether to show wrap guides (vertical rulers) in the editor.
 78    /// Setting this to true will show a guide at the 'preferred_line_length' value
 79    /// if softwrap is set to 'preferred_line_length', and will show any
 80    /// additional guides as specified by the 'wrap_guides' setting.
 81    pub show_wrap_guides: bool,
 82    /// Character counts at which to show wrap guides (vertical rulers) in the editor.
 83    pub wrap_guides: Vec<usize>,
 84    /// Indent guide related settings.
 85    pub indent_guides: IndentGuideSettings,
 86    /// Whether or not to perform a buffer format before saving.
 87    pub format_on_save: FormatOnSave,
 88    /// Whether or not to remove any trailing whitespace from lines of a buffer
 89    /// before saving it.
 90    pub remove_trailing_whitespace_on_save: bool,
 91    /// Whether or not to ensure there's a single newline at the end of a buffer
 92    /// when saving it.
 93    pub ensure_final_newline_on_save: bool,
 94    /// How to perform a buffer format.
 95    pub formatter: settings::FormatterList,
 96    /// Zed's Prettier integration settings.
 97    pub prettier: PrettierSettings,
 98    /// Whether to automatically close JSX tags.
 99    pub jsx_tag_auto_close: bool,
100    /// Whether to use language servers to provide code intelligence.
101    pub enable_language_server: bool,
102    /// The list of language servers to use (or disable) for this language.
103    ///
104    /// This array should consist of language server IDs, as well as the following
105    /// special tokens:
106    /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
107    /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
108    pub language_servers: Vec<String>,
109    /// Controls where the `editor::Rewrap` action is allowed for this language.
110    ///
111    /// Note: This setting has no effect in Vim mode, as rewrap is already
112    /// allowed everywhere.
113    pub allow_rewrap: RewrapBehavior,
114    /// Controls whether edit predictions are shown immediately (true)
115    /// or manually by triggering `editor::ShowEditPrediction` (false).
116    pub show_edit_predictions: bool,
117    /// Controls whether edit predictions are shown in the given language
118    /// scopes.
119    pub edit_predictions_disabled_in: Vec<String>,
120    /// Whether to show tabs and spaces in the editor.
121    pub show_whitespaces: settings::ShowWhitespaceSetting,
122    /// Visible characters used to render whitespace when show_whitespaces is enabled.
123    pub whitespace_map: WhitespaceMap,
124    /// Whether to start a new line with a comment when a previous line is a comment as well.
125    pub extend_comment_on_newline: bool,
126    /// Whether to continue markdown lists when pressing enter.
127    pub extend_list_on_newline: bool,
128    /// Whether to indent list items when pressing tab after a list marker.
129    pub indent_list_on_tab: bool,
130    /// Inlay hint related settings.
131    pub inlay_hints: InlayHintSettings,
132    /// Whether to automatically close brackets.
133    pub use_autoclose: bool,
134    /// Whether to automatically surround text with brackets.
135    pub use_auto_surround: bool,
136    /// Whether to use additional LSP queries to format (and amend) the code after
137    /// every "trigger" symbol input, defined by LSP server capabilities.
138    pub use_on_type_format: bool,
139    /// Whether indentation should be adjusted based on the context whilst typing.
140    pub auto_indent: bool,
141    /// Whether indentation of pasted content should be adjusted based on the context.
142    pub auto_indent_on_paste: bool,
143    /// Controls how the editor handles the autoclosed characters.
144    pub always_treat_brackets_as_autoclosed: bool,
145    /// Which code actions to run on save
146    pub code_actions_on_format: HashMap<String, bool>,
147    /// Whether to perform linked edits
148    pub linked_edits: bool,
149    /// Task configuration for this language.
150    pub tasks: LanguageTaskSettings,
151    /// Whether to pop the completions menu while typing in an editor without
152    /// explicitly requesting it.
153    pub show_completions_on_input: bool,
154    /// Whether to display inline and alongside documentation for items in the
155    /// completions menu.
156    pub show_completion_documentation: bool,
157    /// Completion settings for this language.
158    pub completions: CompletionSettings,
159    /// Preferred debuggers for this language.
160    pub debuggers: Vec<String>,
161    /// Whether to enable word diff highlighting in the editor.
162    ///
163    /// When enabled, changed words within modified lines are highlighted
164    /// to show exactly what changed.
165    ///
166    /// Default: `true`
167    pub word_diff_enabled: bool,
168    /// Whether to use tree-sitter bracket queries to detect and colorize the brackets in the editor.
169    pub colorize_brackets: bool,
170}
171
172#[derive(Debug, Clone, PartialEq)]
173pub struct CompletionSettings {
174    /// Controls how words are completed.
175    /// For large documents, not all words may be fetched for completion.
176    ///
177    /// Default: `fallback`
178    pub words: WordsCompletionMode,
179    /// How many characters has to be in the completions query to automatically show the words-based completions.
180    /// Before that value, it's still possible to trigger the words-based completion manually with the corresponding editor command.
181    ///
182    /// Default: 3
183    pub words_min_length: usize,
184    /// Whether to fetch LSP completions or not.
185    ///
186    /// Default: true
187    pub lsp: bool,
188    /// When fetching LSP completions, determines how long to wait for a response of a particular server.
189    /// When set to 0, waits indefinitely.
190    ///
191    /// Default: 0
192    pub lsp_fetch_timeout_ms: u64,
193    /// Controls how LSP completions are inserted.
194    ///
195    /// Default: "replace_suffix"
196    pub lsp_insert_mode: LspInsertMode,
197}
198
199/// The settings for indent guides.
200#[derive(Debug, Clone, PartialEq)]
201pub struct IndentGuideSettings {
202    /// Whether to display indent guides in the editor.
203    ///
204    /// Default: true
205    pub enabled: bool,
206    /// The width of the indent guides in pixels, between 1 and 10.
207    ///
208    /// Default: 1
209    pub line_width: u32,
210    /// The width of the active indent guide in pixels, between 1 and 10.
211    ///
212    /// Default: 1
213    pub active_line_width: u32,
214    /// Determines how indent guides are colored.
215    ///
216    /// Default: Fixed
217    pub coloring: settings::IndentGuideColoring,
218    /// Determines how indent guide backgrounds are colored.
219    ///
220    /// Default: Disabled
221    pub background_coloring: settings::IndentGuideBackgroundColoring,
222}
223
224#[derive(Debug, Clone, PartialEq)]
225pub struct LanguageTaskSettings {
226    /// Extra task variables to set for a particular language.
227    pub variables: HashMap<String, String>,
228    pub enabled: bool,
229    /// Use LSP tasks over Zed language extension ones.
230    /// If no LSP tasks are returned due to error/timeout or regular execution,
231    /// Zed language extension tasks will be used instead.
232    ///
233    /// Other Zed tasks will still be shown:
234    /// * Zed task from either of the task config file
235    /// * Zed task from history (e.g. one-off task was spawned before)
236    pub prefer_lsp: bool,
237}
238
239/// Allows to enable/disable formatting with Prettier
240/// and configure default Prettier, used when no project-level Prettier installation is found.
241/// Prettier formatting is disabled by default.
242#[derive(Debug, Clone, PartialEq)]
243pub struct PrettierSettings {
244    /// Enables or disables formatting with Prettier for a given language.
245    pub allowed: bool,
246
247    /// Forces Prettier integration to use a specific parser name when formatting files with the language.
248    pub parser: Option<String>,
249
250    /// Forces Prettier integration to use specific plugins when formatting files with the language.
251    /// The default Prettier will be installed with these plugins.
252    pub plugins: HashSet<String>,
253
254    /// Default Prettier options, in the format as in package.json section for Prettier.
255    /// If project installs Prettier via its package.json, these options will be ignored.
256    pub options: HashMap<String, serde_json::Value>,
257}
258
259impl LanguageSettings {
260    /// A token representing the rest of the available language servers.
261    const REST_OF_LANGUAGE_SERVERS: &'static str = "...";
262
263    /// Returns the customized list of language servers from the list of
264    /// available language servers.
265    pub fn customized_language_servers(
266        &self,
267        available_language_servers: &[LanguageServerName],
268    ) -> Vec<LanguageServerName> {
269        Self::resolve_language_servers(&self.language_servers, available_language_servers)
270    }
271
272    pub(crate) fn resolve_language_servers(
273        configured_language_servers: &[String],
274        available_language_servers: &[LanguageServerName],
275    ) -> Vec<LanguageServerName> {
276        let (disabled_language_servers, enabled_language_servers): (
277            Vec<LanguageServerName>,
278            Vec<LanguageServerName>,
279        ) = configured_language_servers.iter().partition_map(
280            |language_server| match language_server.strip_prefix('!') {
281                Some(disabled) => Either::Left(LanguageServerName(disabled.to_string().into())),
282                None => Either::Right(LanguageServerName(language_server.clone().into())),
283            },
284        );
285
286        let rest = available_language_servers
287            .iter()
288            .filter(|&available_language_server| {
289                !disabled_language_servers.contains(available_language_server)
290                    && !enabled_language_servers.contains(available_language_server)
291            })
292            .cloned()
293            .collect::<Vec<_>>();
294
295        enabled_language_servers
296            .into_iter()
297            .flat_map(|language_server| {
298                if language_server.0.as_ref() == Self::REST_OF_LANGUAGE_SERVERS {
299                    rest.clone()
300                } else {
301                    vec![language_server]
302                }
303            })
304            .collect::<Vec<_>>()
305    }
306}
307
308// The settings for inlay hints.
309#[derive(Copy, Clone, Debug, PartialEq, Eq)]
310pub struct InlayHintSettings {
311    /// Global switch to toggle hints on and off.
312    ///
313    /// Default: false
314    pub enabled: bool,
315    /// Global switch to toggle inline values on and off when debugging.
316    ///
317    /// Default: true
318    pub show_value_hints: bool,
319    /// Whether type hints should be shown.
320    ///
321    /// Default: true
322    pub show_type_hints: bool,
323    /// Whether parameter hints should be shown.
324    ///
325    /// Default: true
326    pub show_parameter_hints: bool,
327    /// Whether other hints should be shown.
328    ///
329    /// Default: true
330    pub show_other_hints: bool,
331    /// Whether to show a background for inlay hints.
332    ///
333    /// If set to `true`, the background will use the `hint.background` color
334    /// from the current theme.
335    ///
336    /// Default: false
337    pub show_background: bool,
338    /// Whether or not to debounce inlay hints updates after buffer edits.
339    ///
340    /// Set to 0 to disable debouncing.
341    ///
342    /// Default: 700
343    pub edit_debounce_ms: u64,
344    /// Whether or not to debounce inlay hints updates after buffer scrolls.
345    ///
346    /// Set to 0 to disable debouncing.
347    ///
348    /// Default: 50
349    pub scroll_debounce_ms: u64,
350    /// Toggles inlay hints (hides or shows) when the user presses the modifiers specified.
351    /// If only a subset of the modifiers specified is pressed, hints are not toggled.
352    /// If no modifiers are specified, this is equivalent to `None`.
353    ///
354    /// Default: None
355    pub toggle_on_modifiers_press: Option<Modifiers>,
356}
357
358impl InlayHintSettings {
359    /// Returns the kinds of inlay hints that are enabled based on the settings.
360    pub fn enabled_inlay_hint_kinds(&self) -> HashSet<Option<InlayHintKind>> {
361        let mut kinds = HashSet::default();
362        if self.show_type_hints {
363            kinds.insert(Some(InlayHintKind::Type));
364        }
365        if self.show_parameter_hints {
366            kinds.insert(Some(InlayHintKind::Parameter));
367        }
368        if self.show_other_hints {
369            kinds.insert(None);
370        }
371        kinds
372    }
373}
374
375/// The settings for edit predictions, such as [GitHub Copilot](https://github.com/features/copilot)
376/// or [Supermaven](https://supermaven.com).
377#[derive(Clone, Debug, Default)]
378pub struct EditPredictionSettings {
379    /// The provider that supplies edit predictions.
380    pub provider: settings::EditPredictionProvider,
381    /// A list of globs representing files that edit predictions should be disabled for.
382    /// This list adds to a pre-existing, sensible default set of globs.
383    /// Any additional ones you add are combined with them.
384    pub disabled_globs: Vec<DisabledGlob>,
385    /// Configures how edit predictions are displayed in the buffer.
386    pub mode: settings::EditPredictionsMode,
387    /// Settings specific to GitHub Copilot.
388    pub copilot: CopilotSettings,
389    /// Settings specific to Codestral.
390    pub codestral: CodestralSettings,
391    /// Settings specific to Sweep.
392    pub sweep: SweepSettings,
393    /// Whether edit predictions are enabled in the assistant panel.
394    /// This setting has no effect if globally disabled.
395    pub enabled_in_text_threads: bool,
396    pub examples_dir: Option<Arc<Path>>,
397    pub example_capture_rate: Option<u16>,
398}
399
400impl EditPredictionSettings {
401    /// Returns whether edit predictions are enabled for the given path.
402    pub fn enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
403        !self.disabled_globs.iter().any(|glob| {
404            if glob.is_absolute {
405                file.as_local()
406                    .is_some_and(|local| glob.matcher.is_match(local.abs_path(cx)))
407            } else {
408                glob.matcher.is_match(file.path().as_std_path())
409            }
410        })
411    }
412}
413
414#[derive(Clone, Debug)]
415pub struct DisabledGlob {
416    matcher: GlobMatcher,
417    is_absolute: bool,
418}
419
420#[derive(Clone, Debug, Default)]
421pub struct CopilotSettings {
422    /// HTTP/HTTPS proxy to use for Copilot.
423    pub proxy: Option<String>,
424    /// Disable certificate verification for proxy (not recommended).
425    pub proxy_no_verify: Option<bool>,
426    /// Enterprise URI for Copilot.
427    pub enterprise_uri: Option<String>,
428    /// Whether the Copilot Next Edit Suggestions feature is enabled.
429    pub enable_next_edit_suggestions: Option<bool>,
430}
431
432#[derive(Clone, Debug, Default)]
433pub struct CodestralSettings {
434    /// Model to use for completions.
435    pub model: Option<String>,
436    /// Maximum tokens to generate.
437    pub max_tokens: Option<u32>,
438    /// Custom API URL to use for Codestral.
439    pub api_url: Option<String>,
440}
441
442#[derive(Clone, Debug, Default)]
443pub struct SweepSettings {
444    /// When enabled, Sweep will not store edit prediction inputs or outputs.
445    /// When disabled, Sweep may collect data including buffer contents,
446    /// diagnostics, file paths, repository names, and generated predictions
447    /// to improve the service.
448    pub privacy_mode: bool,
449}
450
451impl AllLanguageSettings {
452    /// Returns the [`LanguageSettings`] for the language with the specified name.
453    pub fn language<'a>(
454        &'a self,
455        location: Option<SettingsLocation<'a>>,
456        language_name: Option<&LanguageName>,
457        cx: &'a App,
458    ) -> Cow<'a, LanguageSettings> {
459        let settings = language_name
460            .and_then(|name| self.languages.get(name))
461            .unwrap_or(&self.defaults);
462
463        let editorconfig_properties = location.and_then(|location| {
464            cx.global::<SettingsStore>()
465                .editorconfig_store
466                .read(cx)
467                .properties(location.worktree_id, location.path)
468        });
469        if let Some(editorconfig_properties) = editorconfig_properties {
470            let mut settings = settings.clone();
471            merge_with_editorconfig(&mut settings, &editorconfig_properties);
472            Cow::Owned(settings)
473        } else {
474            Cow::Borrowed(settings)
475        }
476    }
477
478    /// Returns whether edit predictions are enabled for the given path.
479    pub fn edit_predictions_enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
480        self.edit_predictions.enabled_for_file(file, cx)
481    }
482
483    /// Returns whether edit predictions are enabled for the given language and path.
484    pub fn show_edit_predictions(&self, language: Option<&Arc<Language>>, cx: &App) -> bool {
485        self.language(None, language.map(|l| l.name()).as_ref(), cx)
486            .show_edit_predictions
487    }
488
489    /// Returns the edit predictions preview mode for the given language and path.
490    pub fn edit_predictions_mode(&self) -> EditPredictionsMode {
491        self.edit_predictions.mode
492    }
493}
494
495fn merge_with_editorconfig(settings: &mut LanguageSettings, cfg: &EditorconfigProperties) {
496    let preferred_line_length = cfg.get::<MaxLineLen>().ok().and_then(|v| match v {
497        MaxLineLen::Value(u) => Some(u as u32),
498        MaxLineLen::Off => None,
499    });
500    let tab_size = cfg.get::<IndentSize>().ok().and_then(|v| match v {
501        IndentSize::Value(u) => NonZeroU32::new(u as u32),
502        IndentSize::UseTabWidth => cfg.get::<TabWidth>().ok().and_then(|w| match w {
503            TabWidth::Value(u) => NonZeroU32::new(u as u32),
504        }),
505    });
506    let hard_tabs = cfg
507        .get::<IndentStyle>()
508        .map(|v| v.eq(&IndentStyle::Tabs))
509        .ok();
510    let ensure_final_newline_on_save = cfg
511        .get::<FinalNewline>()
512        .map(|v| match v {
513            FinalNewline::Value(b) => b,
514        })
515        .ok();
516    let remove_trailing_whitespace_on_save = cfg
517        .get::<TrimTrailingWs>()
518        .map(|v| match v {
519            TrimTrailingWs::Value(b) => b,
520        })
521        .ok();
522    fn merge<T>(target: &mut T, value: Option<T>) {
523        if let Some(value) = value {
524            *target = value;
525        }
526    }
527    merge(&mut settings.preferred_line_length, preferred_line_length);
528    merge(&mut settings.tab_size, tab_size);
529    merge(&mut settings.hard_tabs, hard_tabs);
530    merge(
531        &mut settings.remove_trailing_whitespace_on_save,
532        remove_trailing_whitespace_on_save,
533    );
534    merge(
535        &mut settings.ensure_final_newline_on_save,
536        ensure_final_newline_on_save,
537    );
538}
539
540impl settings::Settings for AllLanguageSettings {
541    fn from_settings(content: &settings::SettingsContent) -> Self {
542        let all_languages = &content.project.all_languages;
543
544        fn load_from_content(settings: LanguageSettingsContent) -> LanguageSettings {
545            let inlay_hints = settings.inlay_hints.unwrap();
546            let completions = settings.completions.unwrap();
547            let prettier = settings.prettier.unwrap();
548            let indent_guides = settings.indent_guides.unwrap();
549            let tasks = settings.tasks.unwrap();
550            let whitespace_map = settings.whitespace_map.unwrap();
551
552            LanguageSettings {
553                tab_size: settings.tab_size.unwrap(),
554                hard_tabs: settings.hard_tabs.unwrap(),
555                soft_wrap: settings.soft_wrap.unwrap(),
556                preferred_line_length: settings.preferred_line_length.unwrap(),
557                show_wrap_guides: settings.show_wrap_guides.unwrap(),
558                wrap_guides: settings.wrap_guides.unwrap(),
559                indent_guides: IndentGuideSettings {
560                    enabled: indent_guides.enabled.unwrap(),
561                    line_width: indent_guides.line_width.unwrap(),
562                    active_line_width: indent_guides.active_line_width.unwrap(),
563                    coloring: indent_guides.coloring.unwrap(),
564                    background_coloring: indent_guides.background_coloring.unwrap(),
565                },
566                format_on_save: settings.format_on_save.unwrap(),
567                remove_trailing_whitespace_on_save: settings
568                    .remove_trailing_whitespace_on_save
569                    .unwrap(),
570                ensure_final_newline_on_save: settings.ensure_final_newline_on_save.unwrap(),
571                formatter: settings.formatter.unwrap(),
572                prettier: PrettierSettings {
573                    allowed: prettier.allowed.unwrap(),
574                    parser: prettier.parser.filter(|parser| !parser.is_empty()),
575                    plugins: prettier.plugins.unwrap_or_default(),
576                    options: prettier.options.unwrap_or_default(),
577                },
578                jsx_tag_auto_close: settings.jsx_tag_auto_close.unwrap().enabled.unwrap(),
579                enable_language_server: settings.enable_language_server.unwrap(),
580                language_servers: settings.language_servers.unwrap(),
581                allow_rewrap: settings.allow_rewrap.unwrap(),
582                show_edit_predictions: settings.show_edit_predictions.unwrap(),
583                edit_predictions_disabled_in: settings.edit_predictions_disabled_in.unwrap(),
584                show_whitespaces: settings.show_whitespaces.unwrap(),
585                whitespace_map: WhitespaceMap {
586                    space: SharedString::new(whitespace_map.space.unwrap().to_string()),
587                    tab: SharedString::new(whitespace_map.tab.unwrap().to_string()),
588                },
589                extend_comment_on_newline: settings.extend_comment_on_newline.unwrap(),
590                extend_list_on_newline: settings.extend_list_on_newline.unwrap(),
591                indent_list_on_tab: settings.indent_list_on_tab.unwrap(),
592                inlay_hints: InlayHintSettings {
593                    enabled: inlay_hints.enabled.unwrap(),
594                    show_value_hints: inlay_hints.show_value_hints.unwrap(),
595                    show_type_hints: inlay_hints.show_type_hints.unwrap(),
596                    show_parameter_hints: inlay_hints.show_parameter_hints.unwrap(),
597                    show_other_hints: inlay_hints.show_other_hints.unwrap(),
598                    show_background: inlay_hints.show_background.unwrap(),
599                    edit_debounce_ms: inlay_hints.edit_debounce_ms.unwrap(),
600                    scroll_debounce_ms: inlay_hints.scroll_debounce_ms.unwrap(),
601                    toggle_on_modifiers_press: inlay_hints
602                        .toggle_on_modifiers_press
603                        .map(|m| m.into_gpui()),
604                },
605                use_autoclose: settings.use_autoclose.unwrap(),
606                use_auto_surround: settings.use_auto_surround.unwrap(),
607                use_on_type_format: settings.use_on_type_format.unwrap(),
608                auto_indent: settings.auto_indent.unwrap(),
609                auto_indent_on_paste: settings.auto_indent_on_paste.unwrap(),
610                always_treat_brackets_as_autoclosed: settings
611                    .always_treat_brackets_as_autoclosed
612                    .unwrap(),
613                code_actions_on_format: settings.code_actions_on_format.unwrap(),
614                linked_edits: settings.linked_edits.unwrap(),
615                tasks: LanguageTaskSettings {
616                    variables: tasks.variables.unwrap_or_default(),
617                    enabled: tasks.enabled.unwrap(),
618                    prefer_lsp: tasks.prefer_lsp.unwrap(),
619                },
620                show_completions_on_input: settings.show_completions_on_input.unwrap(),
621                show_completion_documentation: settings.show_completion_documentation.unwrap(),
622                colorize_brackets: settings.colorize_brackets.unwrap(),
623                completions: CompletionSettings {
624                    words: completions.words.unwrap(),
625                    words_min_length: completions.words_min_length.unwrap() as usize,
626                    lsp: completions.lsp.unwrap(),
627                    lsp_fetch_timeout_ms: completions.lsp_fetch_timeout_ms.unwrap(),
628                    lsp_insert_mode: completions.lsp_insert_mode.unwrap(),
629                },
630                debuggers: settings.debuggers.unwrap(),
631                word_diff_enabled: settings.word_diff_enabled.unwrap(),
632            }
633        }
634
635        let default_language_settings = load_from_content(all_languages.defaults.clone());
636
637        let mut languages = HashMap::default();
638        for (language_name, settings) in &all_languages.languages.0 {
639            let mut language_settings = all_languages.defaults.clone();
640            settings::merge_from::MergeFrom::merge_from(&mut language_settings, settings);
641            languages.insert(
642                LanguageName(language_name.clone().into()),
643                load_from_content(language_settings),
644            );
645        }
646
647        let edit_prediction_provider = all_languages
648            .features
649            .as_ref()
650            .and_then(|f| f.edit_prediction_provider);
651
652        let edit_predictions = all_languages.edit_predictions.clone().unwrap();
653        let edit_predictions_mode = edit_predictions.mode.unwrap();
654
655        let disabled_globs: HashSet<&String> = edit_predictions
656            .disabled_globs
657            .as_ref()
658            .unwrap()
659            .iter()
660            .collect();
661
662        let copilot = edit_predictions.copilot.unwrap();
663        let copilot_settings = CopilotSettings {
664            proxy: copilot.proxy,
665            proxy_no_verify: copilot.proxy_no_verify,
666            enterprise_uri: copilot.enterprise_uri,
667            enable_next_edit_suggestions: copilot.enable_next_edit_suggestions,
668        };
669
670        let codestral = edit_predictions.codestral.unwrap();
671        let codestral_settings = CodestralSettings {
672            model: codestral.model,
673            max_tokens: codestral.max_tokens,
674            api_url: codestral.api_url,
675        };
676
677        let sweep = edit_predictions.sweep.unwrap();
678        let sweep_settings = SweepSettings {
679            privacy_mode: sweep.privacy_mode.unwrap(),
680        };
681
682        let enabled_in_text_threads = edit_predictions.enabled_in_text_threads.unwrap();
683
684        let mut file_types: FxHashMap<Arc<str>, (GlobSet, Vec<String>)> = FxHashMap::default();
685
686        for (language, patterns) in all_languages.file_types.iter().flatten() {
687            let mut builder = GlobSetBuilder::new();
688
689            for pattern in &patterns.0 {
690                builder.add(Glob::new(pattern).unwrap());
691            }
692
693            file_types.insert(
694                language.clone(),
695                (builder.build().unwrap(), patterns.0.clone()),
696            );
697        }
698
699        Self {
700            edit_predictions: EditPredictionSettings {
701                provider: if let Some(provider) = edit_prediction_provider {
702                    provider
703                } else {
704                    EditPredictionProvider::None
705                },
706                disabled_globs: disabled_globs
707                    .iter()
708                    .filter_map(|g| {
709                        let expanded_g = shellexpand::tilde(g).into_owned();
710                        Some(DisabledGlob {
711                            matcher: globset::Glob::new(&expanded_g).ok()?.compile_matcher(),
712                            is_absolute: Path::new(&expanded_g).is_absolute(),
713                        })
714                    })
715                    .collect(),
716                mode: edit_predictions_mode,
717                copilot: copilot_settings,
718                codestral: codestral_settings,
719                sweep: sweep_settings,
720                enabled_in_text_threads,
721                examples_dir: edit_predictions.examples_dir,
722                example_capture_rate: edit_predictions.example_capture_rate,
723            },
724            defaults: default_language_settings,
725            languages,
726            file_types,
727        }
728    }
729}
730
731#[derive(Default, Debug, Clone, PartialEq, Eq)]
732pub struct JsxTagAutoCloseSettings {
733    /// Enables or disables auto-closing of JSX tags.
734    pub enabled: bool,
735}
736
737#[cfg(test)]
738mod tests {
739    use super::*;
740    use gpui::TestAppContext;
741    use util::rel_path::rel_path;
742
743    #[gpui::test]
744    fn test_edit_predictions_enabled_for_file(cx: &mut TestAppContext) {
745        use crate::TestFile;
746        use std::path::PathBuf;
747
748        let cx = cx.app.borrow_mut();
749
750        let build_settings = |globs: &[&str]| -> EditPredictionSettings {
751            EditPredictionSettings {
752                disabled_globs: globs
753                    .iter()
754                    .map(|glob_str| {
755                        #[cfg(windows)]
756                        let glob_str = {
757                            let mut g = String::new();
758
759                            if glob_str.starts_with('/') {
760                                g.push_str("C:");
761                            }
762
763                            g.push_str(&glob_str.replace('/', "\\"));
764                            g
765                        };
766                        #[cfg(windows)]
767                        let glob_str = glob_str.as_str();
768                        let expanded_glob_str = shellexpand::tilde(glob_str).into_owned();
769                        DisabledGlob {
770                            matcher: globset::Glob::new(&expanded_glob_str)
771                                .unwrap()
772                                .compile_matcher(),
773                            is_absolute: Path::new(&expanded_glob_str).is_absolute(),
774                        }
775                    })
776                    .collect(),
777                ..Default::default()
778            }
779        };
780
781        const WORKTREE_NAME: &str = "project";
782        let make_test_file = |segments: &[&str]| -> Arc<dyn File> {
783            let path = segments.join("/");
784            let path = rel_path(&path);
785
786            Arc::new(TestFile {
787                path: path.into(),
788                root_name: WORKTREE_NAME.to_string(),
789                local_root: Some(PathBuf::from(if cfg!(windows) {
790                    "C:\\absolute\\"
791                } else {
792                    "/absolute/"
793                })),
794            })
795        };
796
797        let test_file = make_test_file(&["src", "test", "file.rs"]);
798
799        // Test relative globs
800        let settings = build_settings(&["*.rs"]);
801        assert!(!settings.enabled_for_file(&test_file, &cx));
802        let settings = build_settings(&["*.txt"]);
803        assert!(settings.enabled_for_file(&test_file, &cx));
804
805        // Test absolute globs
806        let settings = build_settings(&["/absolute/**/*.rs"]);
807        assert!(!settings.enabled_for_file(&test_file, &cx));
808        let settings = build_settings(&["/other/**/*.rs"]);
809        assert!(settings.enabled_for_file(&test_file, &cx));
810
811        // Test exact path match relative
812        let settings = build_settings(&["src/test/file.rs"]);
813        assert!(!settings.enabled_for_file(&test_file, &cx));
814        let settings = build_settings(&["src/test/otherfile.rs"]);
815        assert!(settings.enabled_for_file(&test_file, &cx));
816
817        // Test exact path match absolute
818        let settings = build_settings(&[&format!("/absolute/{}/src/test/file.rs", WORKTREE_NAME)]);
819        assert!(!settings.enabled_for_file(&test_file, &cx));
820        let settings = build_settings(&["/other/test/otherfile.rs"]);
821        assert!(settings.enabled_for_file(&test_file, &cx));
822
823        // Test * glob
824        let settings = build_settings(&["*"]);
825        assert!(!settings.enabled_for_file(&test_file, &cx));
826        let settings = build_settings(&["*.txt"]);
827        assert!(settings.enabled_for_file(&test_file, &cx));
828
829        // Test **/* glob
830        let settings = build_settings(&["**/*"]);
831        assert!(!settings.enabled_for_file(&test_file, &cx));
832        let settings = build_settings(&["other/**/*"]);
833        assert!(settings.enabled_for_file(&test_file, &cx));
834
835        // Test directory/** glob
836        let settings = build_settings(&["src/**"]);
837        assert!(!settings.enabled_for_file(&test_file, &cx));
838
839        let test_file_root: Arc<dyn File> = Arc::new(TestFile {
840            path: rel_path("file.rs").into(),
841            root_name: WORKTREE_NAME.to_string(),
842            local_root: Some(PathBuf::from("/absolute/")),
843        });
844        assert!(settings.enabled_for_file(&test_file_root, &cx));
845
846        let settings = build_settings(&["other/**"]);
847        assert!(settings.enabled_for_file(&test_file, &cx));
848
849        // Test **/directory/* glob
850        let settings = build_settings(&["**/test/*"]);
851        assert!(!settings.enabled_for_file(&test_file, &cx));
852        let settings = build_settings(&["**/other/*"]);
853        assert!(settings.enabled_for_file(&test_file, &cx));
854
855        // Test multiple globs
856        let settings = build_settings(&["*.rs", "*.txt", "src/**"]);
857        assert!(!settings.enabled_for_file(&test_file, &cx));
858        let settings = build_settings(&["*.txt", "*.md", "other/**"]);
859        assert!(settings.enabled_for_file(&test_file, &cx));
860
861        // Test dot files
862        let dot_file = make_test_file(&[".config", "settings.json"]);
863        let settings = build_settings(&[".*/**"]);
864        assert!(!settings.enabled_for_file(&dot_file, &cx));
865
866        let dot_env_file = make_test_file(&[".env"]);
867        let settings = build_settings(&[".env"]);
868        assert!(!settings.enabled_for_file(&dot_env_file, &cx));
869
870        // Test tilde expansion
871        let home = shellexpand::tilde("~").into_owned();
872        let home_file = Arc::new(TestFile {
873            path: rel_path("test.rs").into(),
874            root_name: "the-dir".to_string(),
875            local_root: Some(PathBuf::from(home)),
876        }) as Arc<dyn File>;
877        let settings = build_settings(&["~/the-dir/test.rs"]);
878        assert!(!settings.enabled_for_file(&home_file, &cx));
879    }
880
881    #[test]
882    fn test_resolve_language_servers() {
883        fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
884            names
885                .iter()
886                .copied()
887                .map(|name| LanguageServerName(name.to_string().into()))
888                .collect::<Vec<_>>()
889        }
890
891        let available_language_servers = language_server_names(&[
892            "typescript-language-server",
893            "biome",
894            "deno",
895            "eslint",
896            "tailwind",
897        ]);
898
899        // A value of just `["..."]` is the same as taking all of the available language servers.
900        assert_eq!(
901            LanguageSettings::resolve_language_servers(
902                &[LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()],
903                &available_language_servers,
904            ),
905            available_language_servers
906        );
907
908        // Referencing one of the available language servers will change its order.
909        assert_eq!(
910            LanguageSettings::resolve_language_servers(
911                &[
912                    "biome".into(),
913                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into(),
914                    "deno".into()
915                ],
916                &available_language_servers
917            ),
918            language_server_names(&[
919                "biome",
920                "typescript-language-server",
921                "eslint",
922                "tailwind",
923                "deno",
924            ])
925        );
926
927        // Negating an available language server removes it from the list.
928        assert_eq!(
929            LanguageSettings::resolve_language_servers(
930                &[
931                    "deno".into(),
932                    "!typescript-language-server".into(),
933                    "!biome".into(),
934                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
935                ],
936                &available_language_servers
937            ),
938            language_server_names(&["deno", "eslint", "tailwind"])
939        );
940
941        // Adding a language server not in the list of available language servers adds it to the list.
942        assert_eq!(
943            LanguageSettings::resolve_language_servers(
944                &[
945                    "my-cool-language-server".into(),
946                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
947                ],
948                &available_language_servers
949            ),
950            language_server_names(&[
951                "my-cool-language-server",
952                "typescript-language-server",
953                "biome",
954                "deno",
955                "eslint",
956                "tailwind",
957            ])
958        );
959    }
960}