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