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