language_settings.rs

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