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