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    /// A list of globs representing files that edit predictions should be disabled for.
382    /// This list adds to a pre-existing, sensible default set of globs.
383    /// Any additional ones you add are combined with them.
384    pub disabled_globs: Vec<DisabledGlob>,
385    /// Configures how edit predictions are displayed in the buffer.
386    pub mode: settings::EditPredictionsMode,
387    /// Settings specific to GitHub Copilot.
388    pub copilot: CopilotSettings,
389    /// Settings specific to Codestral.
390    pub codestral: CodestralSettings,
391    /// Settings specific to Sweep.
392    pub sweep: SweepSettings,
393    /// Settings specific to Ollama.
394    pub ollama: OllamaSettings,
395    /// Whether edit predictions are enabled in the assistant panel.
396    /// This setting has no effect if globally disabled.
397    pub enabled_in_text_threads: bool,
398    pub examples_dir: Option<Arc<Path>>,
399    pub example_capture_rate: Option<u16>,
400}
401
402impl EditPredictionSettings {
403    /// Returns whether edit predictions are enabled for the given path.
404    pub fn enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
405        !self.disabled_globs.iter().any(|glob| {
406            if glob.is_absolute {
407                file.as_local()
408                    .is_some_and(|local| glob.matcher.is_match(local.abs_path(cx)))
409            } else {
410                glob.matcher.is_match(file.path().as_std_path())
411            }
412        })
413    }
414}
415
416#[derive(Clone, Debug)]
417pub struct DisabledGlob {
418    matcher: GlobMatcher,
419    is_absolute: bool,
420}
421
422#[derive(Clone, Debug, Default)]
423pub struct CopilotSettings {
424    /// HTTP/HTTPS proxy to use for Copilot.
425    pub proxy: Option<String>,
426    /// Disable certificate verification for proxy (not recommended).
427    pub proxy_no_verify: Option<bool>,
428    /// Enterprise URI for Copilot.
429    pub enterprise_uri: Option<String>,
430    /// Whether the Copilot Next Edit Suggestions feature is enabled.
431    pub enable_next_edit_suggestions: Option<bool>,
432}
433
434#[derive(Clone, Debug, Default)]
435pub struct CodestralSettings {
436    /// Model to use for completions.
437    pub model: Option<String>,
438    /// Maximum tokens to generate.
439    pub max_tokens: Option<u32>,
440    /// Custom API URL to use for Codestral.
441    pub api_url: Option<String>,
442}
443
444#[derive(Clone, Debug, Default)]
445pub struct SweepSettings {
446    /// When enabled, Sweep will not store edit prediction inputs or outputs.
447    /// When disabled, Sweep may collect data including buffer contents,
448    /// diagnostics, file paths, repository names, and generated predictions
449    /// to improve the service.
450    pub privacy_mode: bool,
451}
452
453#[derive(Clone, Debug, Default)]
454pub struct OllamaSettings {
455    /// Model to use for completions.
456    pub model: Option<String>,
457    /// Maximum tokens to generate.
458    pub max_output_tokens: u32,
459    /// Custom API URL to use for Ollama.
460    pub api_url: Arc<str>,
461}
462
463impl AllLanguageSettings {
464    /// Returns the [`LanguageSettings`] for the language with the specified name.
465    pub fn language<'a>(
466        &'a self,
467        location: Option<SettingsLocation<'a>>,
468        language_name: Option<&LanguageName>,
469        cx: &'a App,
470    ) -> Cow<'a, LanguageSettings> {
471        let settings = language_name
472            .and_then(|name| self.languages.get(name))
473            .unwrap_or(&self.defaults);
474
475        let editorconfig_properties = location.and_then(|location| {
476            cx.global::<SettingsStore>()
477                .editorconfig_store
478                .read(cx)
479                .properties(location.worktree_id, location.path)
480        });
481        if let Some(editorconfig_properties) = editorconfig_properties {
482            let mut settings = settings.clone();
483            merge_with_editorconfig(&mut settings, &editorconfig_properties);
484            Cow::Owned(settings)
485        } else {
486            Cow::Borrowed(settings)
487        }
488    }
489
490    /// Returns whether edit predictions are enabled for the given path.
491    pub fn edit_predictions_enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
492        self.edit_predictions.enabled_for_file(file, cx)
493    }
494
495    /// Returns whether edit predictions are enabled for the given language and path.
496    pub fn show_edit_predictions(&self, language: Option<&Arc<Language>>, cx: &App) -> bool {
497        self.language(None, language.map(|l| l.name()).as_ref(), cx)
498            .show_edit_predictions
499    }
500
501    /// Returns the edit predictions preview mode for the given language and path.
502    pub fn edit_predictions_mode(&self) -> EditPredictionsMode {
503        self.edit_predictions.mode
504    }
505}
506
507fn merge_with_editorconfig(settings: &mut LanguageSettings, cfg: &EditorconfigProperties) {
508    let preferred_line_length = cfg.get::<MaxLineLen>().ok().and_then(|v| match v {
509        MaxLineLen::Value(u) => Some(u as u32),
510        MaxLineLen::Off => None,
511    });
512    let tab_size = cfg.get::<IndentSize>().ok().and_then(|v| match v {
513        IndentSize::Value(u) => NonZeroU32::new(u as u32),
514        IndentSize::UseTabWidth => cfg.get::<TabWidth>().ok().and_then(|w| match w {
515            TabWidth::Value(u) => NonZeroU32::new(u as u32),
516        }),
517    });
518    let hard_tabs = cfg
519        .get::<IndentStyle>()
520        .map(|v| v.eq(&IndentStyle::Tabs))
521        .ok();
522    let ensure_final_newline_on_save = cfg
523        .get::<FinalNewline>()
524        .map(|v| match v {
525            FinalNewline::Value(b) => b,
526        })
527        .ok();
528    let remove_trailing_whitespace_on_save = cfg
529        .get::<TrimTrailingWs>()
530        .map(|v| match v {
531            TrimTrailingWs::Value(b) => b,
532        })
533        .ok();
534    fn merge<T>(target: &mut T, value: Option<T>) {
535        if let Some(value) = value {
536            *target = value;
537        }
538    }
539    merge(&mut settings.preferred_line_length, preferred_line_length);
540    merge(&mut settings.tab_size, tab_size);
541    merge(&mut settings.hard_tabs, hard_tabs);
542    merge(
543        &mut settings.remove_trailing_whitespace_on_save,
544        remove_trailing_whitespace_on_save,
545    );
546    merge(
547        &mut settings.ensure_final_newline_on_save,
548        ensure_final_newline_on_save,
549    );
550}
551
552impl settings::Settings for AllLanguageSettings {
553    fn from_settings(content: &settings::SettingsContent) -> Self {
554        let all_languages = &content.project.all_languages;
555
556        fn load_from_content(settings: LanguageSettingsContent) -> LanguageSettings {
557            let inlay_hints = settings.inlay_hints.unwrap();
558            let completions = settings.completions.unwrap();
559            let prettier = settings.prettier.unwrap();
560            let indent_guides = settings.indent_guides.unwrap();
561            let tasks = settings.tasks.unwrap();
562            let whitespace_map = settings.whitespace_map.unwrap();
563
564            LanguageSettings {
565                tab_size: settings.tab_size.unwrap(),
566                hard_tabs: settings.hard_tabs.unwrap(),
567                soft_wrap: settings.soft_wrap.unwrap(),
568                preferred_line_length: settings.preferred_line_length.unwrap(),
569                show_wrap_guides: settings.show_wrap_guides.unwrap(),
570                wrap_guides: settings.wrap_guides.unwrap(),
571                indent_guides: IndentGuideSettings {
572                    enabled: indent_guides.enabled.unwrap(),
573                    line_width: indent_guides.line_width.unwrap(),
574                    active_line_width: indent_guides.active_line_width.unwrap(),
575                    coloring: indent_guides.coloring.unwrap(),
576                    background_coloring: indent_guides.background_coloring.unwrap(),
577                },
578                format_on_save: settings.format_on_save.unwrap(),
579                remove_trailing_whitespace_on_save: settings
580                    .remove_trailing_whitespace_on_save
581                    .unwrap(),
582                ensure_final_newline_on_save: settings.ensure_final_newline_on_save.unwrap(),
583                formatter: settings.formatter.unwrap(),
584                prettier: PrettierSettings {
585                    allowed: prettier.allowed.unwrap(),
586                    parser: prettier.parser.filter(|parser| !parser.is_empty()),
587                    plugins: prettier.plugins.unwrap_or_default(),
588                    options: prettier.options.unwrap_or_default(),
589                },
590                jsx_tag_auto_close: settings.jsx_tag_auto_close.unwrap().enabled.unwrap(),
591                enable_language_server: settings.enable_language_server.unwrap(),
592                language_servers: settings.language_servers.unwrap(),
593                allow_rewrap: settings.allow_rewrap.unwrap(),
594                show_edit_predictions: settings.show_edit_predictions.unwrap(),
595                edit_predictions_disabled_in: settings.edit_predictions_disabled_in.unwrap(),
596                show_whitespaces: settings.show_whitespaces.unwrap(),
597                whitespace_map: WhitespaceMap {
598                    space: SharedString::new(whitespace_map.space.unwrap().to_string()),
599                    tab: SharedString::new(whitespace_map.tab.unwrap().to_string()),
600                },
601                extend_comment_on_newline: settings.extend_comment_on_newline.unwrap(),
602                extend_list_on_newline: settings.extend_list_on_newline.unwrap(),
603                indent_list_on_tab: settings.indent_list_on_tab.unwrap(),
604                inlay_hints: InlayHintSettings {
605                    enabled: inlay_hints.enabled.unwrap(),
606                    show_value_hints: inlay_hints.show_value_hints.unwrap(),
607                    show_type_hints: inlay_hints.show_type_hints.unwrap(),
608                    show_parameter_hints: inlay_hints.show_parameter_hints.unwrap(),
609                    show_other_hints: inlay_hints.show_other_hints.unwrap(),
610                    show_background: inlay_hints.show_background.unwrap(),
611                    edit_debounce_ms: inlay_hints.edit_debounce_ms.unwrap(),
612                    scroll_debounce_ms: inlay_hints.scroll_debounce_ms.unwrap(),
613                    toggle_on_modifiers_press: inlay_hints
614                        .toggle_on_modifiers_press
615                        .map(|m| m.into_gpui()),
616                },
617                use_autoclose: settings.use_autoclose.unwrap(),
618                use_auto_surround: settings.use_auto_surround.unwrap(),
619                use_on_type_format: settings.use_on_type_format.unwrap(),
620                auto_indent: settings.auto_indent.unwrap(),
621                auto_indent_on_paste: settings.auto_indent_on_paste.unwrap(),
622                always_treat_brackets_as_autoclosed: settings
623                    .always_treat_brackets_as_autoclosed
624                    .unwrap(),
625                code_actions_on_format: settings.code_actions_on_format.unwrap(),
626                linked_edits: settings.linked_edits.unwrap(),
627                tasks: LanguageTaskSettings {
628                    variables: tasks.variables.unwrap_or_default(),
629                    enabled: tasks.enabled.unwrap(),
630                    prefer_lsp: tasks.prefer_lsp.unwrap(),
631                },
632                show_completions_on_input: settings.show_completions_on_input.unwrap(),
633                show_completion_documentation: settings.show_completion_documentation.unwrap(),
634                colorize_brackets: settings.colorize_brackets.unwrap(),
635                completions: CompletionSettings {
636                    words: completions.words.unwrap(),
637                    words_min_length: completions.words_min_length.unwrap() as usize,
638                    lsp: completions.lsp.unwrap(),
639                    lsp_fetch_timeout_ms: completions.lsp_fetch_timeout_ms.unwrap(),
640                    lsp_insert_mode: completions.lsp_insert_mode.unwrap(),
641                },
642                debuggers: settings.debuggers.unwrap(),
643                word_diff_enabled: settings.word_diff_enabled.unwrap(),
644            }
645        }
646
647        let default_language_settings = load_from_content(all_languages.defaults.clone());
648
649        let mut languages = HashMap::default();
650        for (language_name, settings) in &all_languages.languages.0 {
651            let mut language_settings = all_languages.defaults.clone();
652            settings::merge_from::MergeFrom::merge_from(&mut language_settings, settings);
653            languages.insert(
654                LanguageName(language_name.clone().into()),
655                load_from_content(language_settings),
656            );
657        }
658
659        let edit_prediction_provider = all_languages
660            .edit_predictions
661            .as_ref()
662            .and_then(|ep| ep.provider);
663
664        let edit_predictions = all_languages.edit_predictions.clone().unwrap();
665        let edit_predictions_mode = edit_predictions.mode.unwrap();
666
667        let disabled_globs: HashSet<&String> = edit_predictions
668            .disabled_globs
669            .as_ref()
670            .unwrap()
671            .iter()
672            .collect();
673
674        let copilot = edit_predictions.copilot.unwrap();
675        let copilot_settings = CopilotSettings {
676            proxy: copilot.proxy,
677            proxy_no_verify: copilot.proxy_no_verify,
678            enterprise_uri: copilot.enterprise_uri,
679            enable_next_edit_suggestions: copilot.enable_next_edit_suggestions,
680        };
681
682        let codestral = edit_predictions.codestral.unwrap();
683        let codestral_settings = CodestralSettings {
684            model: codestral.model,
685            max_tokens: codestral.max_tokens,
686            api_url: codestral.api_url,
687        };
688
689        let sweep = edit_predictions.sweep.unwrap();
690        let sweep_settings = SweepSettings {
691            privacy_mode: sweep.privacy_mode.unwrap(),
692        };
693        let ollama = edit_predictions.ollama.unwrap();
694        let ollama_settings = OllamaSettings {
695            model: ollama.model.map(|m| m.0),
696            max_output_tokens: ollama.max_output_tokens.unwrap(),
697            api_url: ollama.api_url.unwrap().into(),
698        };
699
700        let enabled_in_text_threads = edit_predictions.enabled_in_text_threads.unwrap();
701
702        let mut file_types: FxHashMap<Arc<str>, (GlobSet, Vec<String>)> = FxHashMap::default();
703
704        for (language, patterns) in all_languages.file_types.iter().flatten() {
705            let mut builder = GlobSetBuilder::new();
706
707            for pattern in &patterns.0 {
708                builder.add(Glob::new(pattern).unwrap());
709            }
710
711            file_types.insert(
712                language.clone(),
713                (builder.build().unwrap(), patterns.0.clone()),
714            );
715        }
716
717        Self {
718            edit_predictions: EditPredictionSettings {
719                provider: if let Some(provider) = edit_prediction_provider {
720                    provider
721                } else {
722                    EditPredictionProvider::None
723                },
724                disabled_globs: disabled_globs
725                    .iter()
726                    .filter_map(|g| {
727                        let expanded_g = shellexpand::tilde(g).into_owned();
728                        Some(DisabledGlob {
729                            matcher: globset::Glob::new(&expanded_g).ok()?.compile_matcher(),
730                            is_absolute: Path::new(&expanded_g).is_absolute(),
731                        })
732                    })
733                    .collect(),
734                mode: edit_predictions_mode,
735                copilot: copilot_settings,
736                codestral: codestral_settings,
737                sweep: sweep_settings,
738                ollama: ollama_settings,
739                enabled_in_text_threads,
740                examples_dir: edit_predictions.examples_dir,
741                example_capture_rate: edit_predictions.example_capture_rate,
742            },
743            defaults: default_language_settings,
744            languages,
745            file_types,
746        }
747    }
748}
749
750#[derive(Default, Debug, Clone, PartialEq, Eq)]
751pub struct JsxTagAutoCloseSettings {
752    /// Enables or disables auto-closing of JSX tags.
753    pub enabled: bool,
754}
755
756#[cfg(test)]
757mod tests {
758    use super::*;
759    use gpui::TestAppContext;
760    use util::rel_path::rel_path;
761
762    #[gpui::test]
763    fn test_edit_predictions_enabled_for_file(cx: &mut TestAppContext) {
764        use crate::TestFile;
765        use std::path::PathBuf;
766
767        let cx = cx.app.borrow_mut();
768
769        let build_settings = |globs: &[&str]| -> EditPredictionSettings {
770            EditPredictionSettings {
771                disabled_globs: globs
772                    .iter()
773                    .map(|glob_str| {
774                        #[cfg(windows)]
775                        let glob_str = {
776                            let mut g = String::new();
777
778                            if glob_str.starts_with('/') {
779                                g.push_str("C:");
780                            }
781
782                            g.push_str(&glob_str.replace('/', "\\"));
783                            g
784                        };
785                        #[cfg(windows)]
786                        let glob_str = glob_str.as_str();
787                        let expanded_glob_str = shellexpand::tilde(glob_str).into_owned();
788                        DisabledGlob {
789                            matcher: globset::Glob::new(&expanded_glob_str)
790                                .unwrap()
791                                .compile_matcher(),
792                            is_absolute: Path::new(&expanded_glob_str).is_absolute(),
793                        }
794                    })
795                    .collect(),
796                ..Default::default()
797            }
798        };
799
800        const WORKTREE_NAME: &str = "project";
801        let make_test_file = |segments: &[&str]| -> Arc<dyn File> {
802            let path = segments.join("/");
803            let path = rel_path(&path);
804
805            Arc::new(TestFile {
806                path: path.into(),
807                root_name: WORKTREE_NAME.to_string(),
808                local_root: Some(PathBuf::from(if cfg!(windows) {
809                    "C:\\absolute\\"
810                } else {
811                    "/absolute/"
812                })),
813            })
814        };
815
816        let test_file = make_test_file(&["src", "test", "file.rs"]);
817
818        // Test relative globs
819        let settings = build_settings(&["*.rs"]);
820        assert!(!settings.enabled_for_file(&test_file, &cx));
821        let settings = build_settings(&["*.txt"]);
822        assert!(settings.enabled_for_file(&test_file, &cx));
823
824        // Test absolute globs
825        let settings = build_settings(&["/absolute/**/*.rs"]);
826        assert!(!settings.enabled_for_file(&test_file, &cx));
827        let settings = build_settings(&["/other/**/*.rs"]);
828        assert!(settings.enabled_for_file(&test_file, &cx));
829
830        // Test exact path match relative
831        let settings = build_settings(&["src/test/file.rs"]);
832        assert!(!settings.enabled_for_file(&test_file, &cx));
833        let settings = build_settings(&["src/test/otherfile.rs"]);
834        assert!(settings.enabled_for_file(&test_file, &cx));
835
836        // Test exact path match absolute
837        let settings = build_settings(&[&format!("/absolute/{}/src/test/file.rs", WORKTREE_NAME)]);
838        assert!(!settings.enabled_for_file(&test_file, &cx));
839        let settings = build_settings(&["/other/test/otherfile.rs"]);
840        assert!(settings.enabled_for_file(&test_file, &cx));
841
842        // Test * glob
843        let settings = build_settings(&["*"]);
844        assert!(!settings.enabled_for_file(&test_file, &cx));
845        let settings = build_settings(&["*.txt"]);
846        assert!(settings.enabled_for_file(&test_file, &cx));
847
848        // Test **/* glob
849        let settings = build_settings(&["**/*"]);
850        assert!(!settings.enabled_for_file(&test_file, &cx));
851        let settings = build_settings(&["other/**/*"]);
852        assert!(settings.enabled_for_file(&test_file, &cx));
853
854        // Test directory/** glob
855        let settings = build_settings(&["src/**"]);
856        assert!(!settings.enabled_for_file(&test_file, &cx));
857
858        let test_file_root: Arc<dyn File> = Arc::new(TestFile {
859            path: rel_path("file.rs").into(),
860            root_name: WORKTREE_NAME.to_string(),
861            local_root: Some(PathBuf::from("/absolute/")),
862        });
863        assert!(settings.enabled_for_file(&test_file_root, &cx));
864
865        let settings = build_settings(&["other/**"]);
866        assert!(settings.enabled_for_file(&test_file, &cx));
867
868        // Test **/directory/* glob
869        let settings = build_settings(&["**/test/*"]);
870        assert!(!settings.enabled_for_file(&test_file, &cx));
871        let settings = build_settings(&["**/other/*"]);
872        assert!(settings.enabled_for_file(&test_file, &cx));
873
874        // Test multiple globs
875        let settings = build_settings(&["*.rs", "*.txt", "src/**"]);
876        assert!(!settings.enabled_for_file(&test_file, &cx));
877        let settings = build_settings(&["*.txt", "*.md", "other/**"]);
878        assert!(settings.enabled_for_file(&test_file, &cx));
879
880        // Test dot files
881        let dot_file = make_test_file(&[".config", "settings.json"]);
882        let settings = build_settings(&[".*/**"]);
883        assert!(!settings.enabled_for_file(&dot_file, &cx));
884
885        let dot_env_file = make_test_file(&[".env"]);
886        let settings = build_settings(&[".env"]);
887        assert!(!settings.enabled_for_file(&dot_env_file, &cx));
888
889        // Test tilde expansion
890        let home = shellexpand::tilde("~").into_owned();
891        let home_file = Arc::new(TestFile {
892            path: rel_path("test.rs").into(),
893            root_name: "the-dir".to_string(),
894            local_root: Some(PathBuf::from(home)),
895        }) as Arc<dyn File>;
896        let settings = build_settings(&["~/the-dir/test.rs"]);
897        assert!(!settings.enabled_for_file(&home_file, &cx));
898    }
899
900    #[test]
901    fn test_resolve_language_servers() {
902        fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
903            names
904                .iter()
905                .copied()
906                .map(|name| LanguageServerName(name.to_string().into()))
907                .collect::<Vec<_>>()
908        }
909
910        let available_language_servers = language_server_names(&[
911            "typescript-language-server",
912            "biome",
913            "deno",
914            "eslint",
915            "tailwind",
916        ]);
917
918        // A value of just `["..."]` is the same as taking all of the available language servers.
919        assert_eq!(
920            LanguageSettings::resolve_language_servers(
921                &[LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()],
922                &available_language_servers,
923            ),
924            available_language_servers
925        );
926
927        // Referencing one of the available language servers will change its order.
928        assert_eq!(
929            LanguageSettings::resolve_language_servers(
930                &[
931                    "biome".into(),
932                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into(),
933                    "deno".into()
934                ],
935                &available_language_servers
936            ),
937            language_server_names(&[
938                "biome",
939                "typescript-language-server",
940                "eslint",
941                "tailwind",
942                "deno",
943            ])
944        );
945
946        // Negating an available language server removes it from the list.
947        assert_eq!(
948            LanguageSettings::resolve_language_servers(
949                &[
950                    "deno".into(),
951                    "!typescript-language-server".into(),
952                    "!biome".into(),
953                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
954                ],
955                &available_language_servers
956            ),
957            language_server_names(&["deno", "eslint", "tailwind"])
958        );
959
960        // Adding a language server not in the list of available language servers adds it to the list.
961        assert_eq!(
962            LanguageSettings::resolve_language_servers(
963                &[
964                    "my-cool-language-server".into(),
965                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
966                ],
967                &available_language_servers
968            ),
969            language_server_names(&[
970                "my-cool-language-server",
971                "typescript-language-server",
972                "biome",
973                "deno",
974                "eslint",
975                "tailwind",
976            ])
977        );
978    }
979}