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