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