language_settings.rs

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