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