language_settings.rs

   1//! Provides `language`-related settings.
   2
   3use crate::{File, Language, LanguageName, LanguageServerName};
   4use anyhow::Result;
   5use collections::{FxHashMap, HashMap, HashSet};
   6use ec4rs::{
   7    Properties as EditorconfigProperties,
   8    property::{FinalNewline, IndentSize, IndentStyle, MaxLineLen, TabWidth, TrimTrailingWs},
   9};
  10use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
  11use gpui::{App, Modifiers, SharedString};
  12use itertools::{Either, Itertools};
  13use schemars::{JsonSchema, json_schema};
  14use serde::{
  15    Deserialize, Deserializer, Serialize,
  16    de::{self, IntoDeserializer, MapAccess, SeqAccess, Visitor},
  17};
  18
  19use settings::{
  20    ParameterizedJsonSchema, Settings, SettingsKey, SettingsLocation, SettingsSources,
  21    SettingsStore, SettingsUi,
  22};
  23use shellexpand;
  24use std::{borrow::Cow, num::NonZeroU32, path::Path, slice, sync::Arc};
  25use util::schemars::replace_subschema;
  26use util::serde::default_true;
  27
  28/// Initializes the language settings.
  29pub fn init(cx: &mut App) {
  30    AllLanguageSettings::register(cx);
  31}
  32
  33/// Returns the settings for the specified language from the provided file.
  34pub fn language_settings<'a>(
  35    language: Option<LanguageName>,
  36    file: Option<&'a Arc<dyn File>>,
  37    cx: &'a App,
  38) -> Cow<'a, LanguageSettings> {
  39    let location = file.map(|f| SettingsLocation {
  40        worktree_id: f.worktree_id(cx),
  41        path: f.path().as_ref(),
  42    });
  43    AllLanguageSettings::get(location, cx).language(location, language.as_ref(), cx)
  44}
  45
  46/// Returns the settings for all languages from the provided file.
  47pub fn all_language_settings<'a>(
  48    file: Option<&'a Arc<dyn File>>,
  49    cx: &'a App,
  50) -> &'a AllLanguageSettings {
  51    let location = file.map(|f| SettingsLocation {
  52        worktree_id: f.worktree_id(cx),
  53        path: f.path().as_ref(),
  54    });
  55    AllLanguageSettings::get(location, cx)
  56}
  57
  58/// The settings for all languages.
  59#[derive(Debug, Clone)]
  60pub struct AllLanguageSettings {
  61    /// The edit prediction settings.
  62    pub edit_predictions: EditPredictionSettings,
  63    pub defaults: LanguageSettings,
  64    languages: HashMap<LanguageName, LanguageSettings>,
  65    pub(crate) file_types: FxHashMap<Arc<str>, GlobSet>,
  66}
  67
  68/// The settings for a particular language.
  69#[derive(Debug, Clone, Deserialize)]
  70pub struct LanguageSettings {
  71    /// How many columns a tab should occupy.
  72    pub tab_size: NonZeroU32,
  73    /// Whether to indent lines using tab characters, as opposed to multiple
  74    /// spaces.
  75    pub hard_tabs: bool,
  76    /// How to soft-wrap long lines of text.
  77    pub soft_wrap: SoftWrap,
  78    /// The column at which to soft-wrap lines, for buffers where soft-wrap
  79    /// is enabled.
  80    pub preferred_line_length: u32,
  81    /// Whether to show wrap guides (vertical rulers) in the editor.
  82    /// Setting this to true will show a guide at the 'preferred_line_length' value
  83    /// if softwrap is set to 'preferred_line_length', and will show any
  84    /// additional guides as specified by the 'wrap_guides' setting.
  85    pub show_wrap_guides: bool,
  86    /// Character counts at which to show wrap guides (vertical rulers) in the editor.
  87    pub wrap_guides: Vec<usize>,
  88    /// Indent guide related settings.
  89    pub indent_guides: IndentGuideSettings,
  90    /// Whether or not to perform a buffer format before saving.
  91    pub format_on_save: FormatOnSave,
  92    /// Whether or not to remove any trailing whitespace from lines of a buffer
  93    /// before saving it.
  94    pub remove_trailing_whitespace_on_save: bool,
  95    /// Whether or not to ensure there's a single newline at the end of a buffer
  96    /// when saving it.
  97    pub ensure_final_newline_on_save: bool,
  98    /// How to perform a buffer format.
  99    pub formatter: SelectedFormatter,
 100    /// Zed's Prettier integration settings.
 101    pub prettier: PrettierSettings,
 102    /// Whether to automatically close JSX tags.
 103    pub jsx_tag_auto_close: JsxTagAutoCloseSettings,
 104    /// Whether to use language servers to provide code intelligence.
 105    pub enable_language_server: bool,
 106    /// The list of language servers to use (or disable) for this language.
 107    ///
 108    /// This array should consist of language server IDs, as well as the following
 109    /// special tokens:
 110    /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
 111    /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
 112    pub language_servers: Vec<String>,
 113    /// Controls where the `editor::Rewrap` action is allowed for this language.
 114    ///
 115    /// Note: This setting has no effect in Vim mode, as rewrap is already
 116    /// allowed everywhere.
 117    pub allow_rewrap: RewrapBehavior,
 118    /// Controls whether edit predictions are shown immediately (true)
 119    /// or manually by triggering `editor::ShowEditPrediction` (false).
 120    pub show_edit_predictions: bool,
 121    /// Controls whether edit predictions are shown in the given language
 122    /// scopes.
 123    pub edit_predictions_disabled_in: Vec<String>,
 124    /// Whether to show tabs and spaces in the editor.
 125    pub show_whitespaces: ShowWhitespaceSetting,
 126    /// Visible characters used to render whitespace when show_whitespaces is enabled.
 127    pub whitespace_map: WhitespaceMap,
 128    /// Whether to start a new line with a comment when a previous line is a comment as well.
 129    pub extend_comment_on_newline: bool,
 130    /// Inlay hint related settings.
 131    pub inlay_hints: InlayHintSettings,
 132    /// Whether to automatically close brackets.
 133    pub use_autoclose: bool,
 134    /// Whether to automatically surround text with brackets.
 135    pub use_auto_surround: bool,
 136    /// Whether to use additional LSP queries to format (and amend) the code after
 137    /// every "trigger" symbol input, defined by LSP server capabilities.
 138    pub use_on_type_format: bool,
 139    /// Whether indentation should be adjusted based on the context whilst typing.
 140    pub auto_indent: bool,
 141    /// Whether indentation of pasted content should be adjusted based on the context.
 142    pub auto_indent_on_paste: bool,
 143    /// Controls how the editor handles the autoclosed characters.
 144    pub always_treat_brackets_as_autoclosed: bool,
 145    /// Which code actions to run on save
 146    pub code_actions_on_format: HashMap<String, bool>,
 147    /// Whether to perform linked edits
 148    pub linked_edits: bool,
 149    /// Task configuration for this language.
 150    pub tasks: LanguageTaskConfig,
 151    /// Whether to pop the completions menu while typing in an editor without
 152    /// explicitly requesting it.
 153    pub show_completions_on_input: bool,
 154    /// Whether to display inline and alongside documentation for items in the
 155    /// completions menu.
 156    pub show_completion_documentation: bool,
 157    /// Completion settings for this language.
 158    pub completions: CompletionSettings,
 159    /// Preferred debuggers for this language.
 160    pub debuggers: Vec<String>,
 161}
 162
 163impl LanguageSettings {
 164    /// A token representing the rest of the available language servers.
 165    const REST_OF_LANGUAGE_SERVERS: &'static str = "...";
 166
 167    /// Returns the customized list of language servers from the list of
 168    /// available language servers.
 169    pub fn customized_language_servers(
 170        &self,
 171        available_language_servers: &[LanguageServerName],
 172    ) -> Vec<LanguageServerName> {
 173        Self::resolve_language_servers(&self.language_servers, available_language_servers)
 174    }
 175
 176    pub(crate) fn resolve_language_servers(
 177        configured_language_servers: &[String],
 178        available_language_servers: &[LanguageServerName],
 179    ) -> Vec<LanguageServerName> {
 180        let (disabled_language_servers, enabled_language_servers): (
 181            Vec<LanguageServerName>,
 182            Vec<LanguageServerName>,
 183        ) = configured_language_servers.iter().partition_map(
 184            |language_server| match language_server.strip_prefix('!') {
 185                Some(disabled) => Either::Left(LanguageServerName(disabled.to_string().into())),
 186                None => Either::Right(LanguageServerName(language_server.clone().into())),
 187            },
 188        );
 189
 190        let rest = available_language_servers
 191            .iter()
 192            .filter(|&available_language_server| {
 193                !disabled_language_servers.contains(available_language_server)
 194                    && !enabled_language_servers.contains(available_language_server)
 195            })
 196            .cloned()
 197            .collect::<Vec<_>>();
 198
 199        enabled_language_servers
 200            .into_iter()
 201            .flat_map(|language_server| {
 202                if language_server.0.as_ref() == Self::REST_OF_LANGUAGE_SERVERS {
 203                    rest.clone()
 204                } else {
 205                    vec![language_server]
 206                }
 207            })
 208            .collect::<Vec<_>>()
 209    }
 210}
 211
 212/// The provider that supplies edit predictions.
 213#[derive(
 214    Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema, SettingsUi,
 215)]
 216#[serde(rename_all = "snake_case")]
 217pub enum EditPredictionProvider {
 218    None,
 219    #[default]
 220    Copilot,
 221    Supermaven,
 222    Zed,
 223}
 224
 225impl EditPredictionProvider {
 226    pub fn is_zed(&self) -> bool {
 227        match self {
 228            EditPredictionProvider::Zed => true,
 229            EditPredictionProvider::None
 230            | EditPredictionProvider::Copilot
 231            | EditPredictionProvider::Supermaven => false,
 232        }
 233    }
 234}
 235
 236/// The settings for edit predictions, such as [GitHub Copilot](https://github.com/features/copilot)
 237/// or [Supermaven](https://supermaven.com).
 238#[derive(Clone, Debug, Default, SettingsUi)]
 239pub struct EditPredictionSettings {
 240    /// The provider that supplies edit predictions.
 241    pub provider: EditPredictionProvider,
 242    /// A list of globs representing files that edit predictions should be disabled for.
 243    /// This list adds to a pre-existing, sensible default set of globs.
 244    /// Any additional ones you add are combined with them.
 245    #[settings_ui(skip)]
 246    pub disabled_globs: Vec<DisabledGlob>,
 247    /// Configures how edit predictions are displayed in the buffer.
 248    pub mode: EditPredictionsMode,
 249    /// Settings specific to GitHub Copilot.
 250    pub copilot: CopilotSettings,
 251    /// Whether edit predictions are enabled in the assistant panel.
 252    /// This setting has no effect if globally disabled.
 253    pub enabled_in_text_threads: bool,
 254}
 255
 256impl EditPredictionSettings {
 257    /// Returns whether edit predictions are enabled for the given path.
 258    pub fn enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
 259        !self.disabled_globs.iter().any(|glob| {
 260            if glob.is_absolute {
 261                file.as_local()
 262                    .is_some_and(|local| glob.matcher.is_match(local.abs_path(cx)))
 263            } else {
 264                glob.matcher.is_match(file.path())
 265            }
 266        })
 267    }
 268}
 269
 270#[derive(Clone, Debug)]
 271pub struct DisabledGlob {
 272    matcher: GlobMatcher,
 273    is_absolute: bool,
 274}
 275
 276/// The mode in which edit predictions should be displayed.
 277#[derive(
 278    Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema, SettingsUi,
 279)]
 280#[serde(rename_all = "snake_case")]
 281pub enum EditPredictionsMode {
 282    /// If provider supports it, display inline when holding modifier key (e.g., alt).
 283    /// Otherwise, eager preview is used.
 284    #[serde(alias = "auto")]
 285    Subtle,
 286    /// Display inline when there are no language server completions available.
 287    #[default]
 288    #[serde(alias = "eager_preview")]
 289    Eager,
 290}
 291
 292#[derive(Clone, Debug, Default, SettingsUi)]
 293pub struct CopilotSettings {
 294    /// HTTP/HTTPS proxy to use for Copilot.
 295    #[settings_ui(skip)]
 296    pub proxy: Option<String>,
 297    /// Disable certificate verification for proxy (not recommended).
 298    pub proxy_no_verify: Option<bool>,
 299    /// Enterprise URI for Copilot.
 300    #[settings_ui(skip)]
 301    pub enterprise_uri: Option<String>,
 302}
 303
 304/// The settings for all languages.
 305#[derive(
 306    Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, SettingsUi, SettingsKey,
 307)]
 308#[settings_key(None)]
 309#[settings_ui(group = "Default Language Settings")]
 310pub struct AllLanguageSettingsContent {
 311    /// The settings for enabling/disabling features.
 312    #[serde(default)]
 313    pub features: Option<FeaturesContent>,
 314    /// The edit prediction settings.
 315    #[serde(default)]
 316    pub edit_predictions: Option<EditPredictionSettingsContent>,
 317    /// The default language settings.
 318    #[serde(flatten)]
 319    pub defaults: LanguageSettingsContent,
 320    /// The settings for individual languages.
 321    #[serde(default)]
 322    pub languages: LanguageToSettingsMap,
 323    /// Settings for associating file extensions and filenames
 324    /// with languages.
 325    #[serde(default)]
 326    #[settings_ui(skip)]
 327    pub file_types: HashMap<Arc<str>, Vec<String>>,
 328}
 329
 330/// Map from language name to settings. Its `ParameterizedJsonSchema` allows only known language
 331/// names in the keys.
 332#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
 333pub struct LanguageToSettingsMap(pub HashMap<LanguageName, LanguageSettingsContent>);
 334
 335impl SettingsUi for LanguageToSettingsMap {
 336    fn settings_ui_item() -> settings::SettingsUiItem {
 337        settings::SettingsUiItem::DynamicMap(settings::SettingsUiItemDynamicMap {
 338            item: LanguageSettingsContent::settings_ui_item,
 339            defaults_path: &[],
 340            determine_items: |settings_value, cx| {
 341                use settings::SettingsUiEntryMetaData;
 342
 343                // todo(settings_ui): We should be using a global LanguageRegistry, but it's not implemented yet
 344                _ = cx;
 345
 346                let Some(settings_language_map) = settings_value.as_object() else {
 347                    return Vec::new();
 348                };
 349                let mut languages = Vec::with_capacity(settings_language_map.len());
 350
 351                for language_name in settings_language_map.keys().map(gpui::SharedString::from) {
 352                    languages.push(SettingsUiEntryMetaData {
 353                        title: language_name.clone(),
 354                        path: language_name,
 355                        // todo(settings_ui): Implement documentation for each language
 356                        // ideally based on the language's official docs from extension or builtin info
 357                        documentation: None,
 358                    });
 359                }
 360                return languages;
 361            },
 362        })
 363    }
 364}
 365
 366inventory::submit! {
 367    ParameterizedJsonSchema {
 368        add_and_get_ref: |generator, params, _cx| {
 369            let language_settings_content_ref = generator
 370                .subschema_for::<LanguageSettingsContent>()
 371                .to_value();
 372            replace_subschema::<LanguageToSettingsMap>(generator, || json_schema!({
 373                "type": "object",
 374                "properties": params
 375                    .language_names
 376                    .iter()
 377                    .map(|name| {
 378                        (
 379                            name.clone(),
 380                            language_settings_content_ref.clone(),
 381                        )
 382                    })
 383                    .collect::<serde_json::Map<_, _>>()
 384            }))
 385        }
 386    }
 387}
 388
 389/// Controls how completions are processed for this language.
 390#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, SettingsUi)]
 391#[serde(rename_all = "snake_case")]
 392pub struct CompletionSettings {
 393    /// Controls how words are completed.
 394    /// For large documents, not all words may be fetched for completion.
 395    ///
 396    /// Default: `fallback`
 397    #[serde(default = "default_words_completion_mode")]
 398    pub words: WordsCompletionMode,
 399    /// How many characters has to be in the completions query to automatically show the words-based completions.
 400    /// Before that value, it's still possible to trigger the words-based completion manually with the corresponding editor command.
 401    ///
 402    /// Default: 3
 403    #[serde(default = "default_3")]
 404    pub words_min_length: usize,
 405    /// Whether to fetch LSP completions or not.
 406    ///
 407    /// Default: true
 408    #[serde(default = "default_true")]
 409    pub lsp: bool,
 410    /// When fetching LSP completions, determines how long to wait for a response of a particular server.
 411    /// When set to 0, waits indefinitely.
 412    ///
 413    /// Default: 0
 414    #[serde(default)]
 415    pub lsp_fetch_timeout_ms: u64,
 416    /// Controls how LSP completions are inserted.
 417    ///
 418    /// Default: "replace_suffix"
 419    #[serde(default = "default_lsp_insert_mode")]
 420    pub lsp_insert_mode: LspInsertMode,
 421}
 422
 423/// Controls how document's words are completed.
 424#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
 425#[serde(rename_all = "snake_case")]
 426pub enum WordsCompletionMode {
 427    /// Always fetch document's words for completions along with LSP completions.
 428    Enabled,
 429    /// Only if LSP response errors or times out,
 430    /// use document's words to show completions.
 431    Fallback,
 432    /// Never fetch or complete document's words for completions.
 433    /// (Word-based completions can still be queried via a separate action)
 434    Disabled,
 435}
 436
 437#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
 438#[serde(rename_all = "snake_case")]
 439pub enum LspInsertMode {
 440    /// Replaces text before the cursor, using the `insert` range described in the LSP specification.
 441    Insert,
 442    /// Replaces text before and after the cursor, using the `replace` range described in the LSP specification.
 443    Replace,
 444    /// Behaves like `"replace"` if the text that would be replaced is a subsequence of the completion text,
 445    /// and like `"insert"` otherwise.
 446    ReplaceSubsequence,
 447    /// Behaves like `"replace"` if the text after the cursor is a suffix of the completion, and like
 448    /// `"insert"` otherwise.
 449    ReplaceSuffix,
 450}
 451
 452fn default_words_completion_mode() -> WordsCompletionMode {
 453    WordsCompletionMode::Fallback
 454}
 455
 456fn default_lsp_insert_mode() -> LspInsertMode {
 457    LspInsertMode::ReplaceSuffix
 458}
 459
 460fn default_3() -> usize {
 461    3
 462}
 463
 464/// The settings for a particular language.
 465#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, SettingsUi)]
 466#[settings_ui(group = "Default")]
 467pub struct LanguageSettingsContent {
 468    /// How many columns a tab should occupy.
 469    ///
 470    /// Default: 4
 471    #[serde(default)]
 472    #[settings_ui(skip)]
 473    pub tab_size: Option<NonZeroU32>,
 474    /// Whether to indent lines using tab characters, as opposed to multiple
 475    /// spaces.
 476    ///
 477    /// Default: false
 478    #[serde(default)]
 479    pub hard_tabs: Option<bool>,
 480    /// How to soft-wrap long lines of text.
 481    ///
 482    /// Default: none
 483    #[serde(default)]
 484    pub soft_wrap: Option<SoftWrap>,
 485    /// The column at which to soft-wrap lines, for buffers where soft-wrap
 486    /// is enabled.
 487    ///
 488    /// Default: 80
 489    #[serde(default)]
 490    pub preferred_line_length: Option<u32>,
 491    /// Whether to show wrap guides in the editor. Setting this to true will
 492    /// show a guide at the 'preferred_line_length' value if softwrap is set to
 493    /// 'preferred_line_length', and will show any additional guides as specified
 494    /// by the 'wrap_guides' setting.
 495    ///
 496    /// Default: true
 497    #[serde(default)]
 498    pub show_wrap_guides: Option<bool>,
 499    /// Character counts at which to show wrap guides in the editor.
 500    ///
 501    /// Default: []
 502    #[serde(default)]
 503    #[settings_ui(skip)]
 504    pub wrap_guides: Option<Vec<usize>>,
 505    /// Indent guide related settings.
 506    #[serde(default)]
 507    pub indent_guides: Option<IndentGuideSettings>,
 508    /// Whether or not to perform a buffer format before saving.
 509    ///
 510    /// Default: on
 511    #[serde(default)]
 512    pub format_on_save: Option<FormatOnSave>,
 513    /// Whether or not to remove any trailing whitespace from lines of a buffer
 514    /// before saving it.
 515    ///
 516    /// Default: true
 517    #[serde(default)]
 518    pub remove_trailing_whitespace_on_save: Option<bool>,
 519    /// Whether or not to ensure there's a single newline at the end of a buffer
 520    /// when saving it.
 521    ///
 522    /// Default: true
 523    #[serde(default)]
 524    pub ensure_final_newline_on_save: Option<bool>,
 525    /// How to perform a buffer format.
 526    ///
 527    /// Default: auto
 528    #[serde(default)]
 529    #[settings_ui(skip)]
 530    pub formatter: Option<SelectedFormatter>,
 531    /// Zed's Prettier integration settings.
 532    /// Allows to enable/disable formatting with Prettier
 533    /// and configure default Prettier, used when no project-level Prettier installation is found.
 534    ///
 535    /// Default: off
 536    #[serde(default)]
 537    pub prettier: Option<PrettierSettings>,
 538    /// Whether to automatically close JSX tags.
 539    #[serde(default)]
 540    pub jsx_tag_auto_close: Option<JsxTagAutoCloseSettings>,
 541    /// Whether to use language servers to provide code intelligence.
 542    ///
 543    /// Default: true
 544    #[serde(default)]
 545    pub enable_language_server: Option<bool>,
 546    /// The list of language servers to use (or disable) for this language.
 547    ///
 548    /// This array should consist of language server IDs, as well as the following
 549    /// special tokens:
 550    /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
 551    /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
 552    ///
 553    /// Default: ["..."]
 554    #[serde(default)]
 555    pub language_servers: Option<Vec<String>>,
 556    /// Controls where the `editor::Rewrap` action is allowed for this language.
 557    ///
 558    /// Note: This setting has no effect in Vim mode, as rewrap is already
 559    /// allowed everywhere.
 560    ///
 561    /// Default: "in_comments"
 562    #[serde(default)]
 563    pub allow_rewrap: Option<RewrapBehavior>,
 564    /// Controls whether edit predictions are shown immediately (true)
 565    /// or manually by triggering `editor::ShowEditPrediction` (false).
 566    ///
 567    /// Default: true
 568    #[serde(default)]
 569    pub show_edit_predictions: Option<bool>,
 570    /// Controls whether edit predictions are shown in the given language
 571    /// scopes.
 572    ///
 573    /// Example: ["string", "comment"]
 574    ///
 575    /// Default: []
 576    #[serde(default)]
 577    #[settings_ui(skip)]
 578    pub edit_predictions_disabled_in: Option<Vec<String>>,
 579    /// Whether to show tabs and spaces in the editor.
 580    #[serde(default)]
 581    pub show_whitespaces: Option<ShowWhitespaceSetting>,
 582    /// Visible characters used to render whitespace when show_whitespaces is enabled.
 583    ///
 584    /// Default: "•" for spaces, "→" for tabs.
 585    #[serde(default)]
 586    pub whitespace_map: Option<WhitespaceMap>,
 587    /// Whether to start a new line with a comment when a previous line is a comment as well.
 588    ///
 589    /// Default: true
 590    #[serde(default)]
 591    pub extend_comment_on_newline: Option<bool>,
 592    /// Inlay hint related settings.
 593    #[serde(default)]
 594    pub inlay_hints: Option<InlayHintSettings>,
 595    /// Whether to automatically type closing characters for you. For example,
 596    /// when you type (, Zed will automatically add a closing ) at the correct position.
 597    ///
 598    /// Default: true
 599    pub use_autoclose: Option<bool>,
 600    /// Whether to automatically surround text with characters for you. For example,
 601    /// when you select text and type (, Zed will automatically surround text with ().
 602    ///
 603    /// Default: true
 604    pub use_auto_surround: Option<bool>,
 605    /// Controls how the editor handles the autoclosed characters.
 606    /// When set to `false`(default), skipping over and auto-removing of the closing characters
 607    /// happen only for auto-inserted characters.
 608    /// Otherwise(when `true`), the closing characters are always skipped over and auto-removed
 609    /// no matter how they were inserted.
 610    ///
 611    /// Default: false
 612    pub always_treat_brackets_as_autoclosed: Option<bool>,
 613    /// Whether to use additional LSP queries to format (and amend) the code after
 614    /// every "trigger" symbol input, defined by LSP server capabilities.
 615    ///
 616    /// Default: true
 617    pub use_on_type_format: Option<bool>,
 618    /// Which code actions to run on save after the formatter.
 619    /// These are not run if formatting is off.
 620    ///
 621    /// Default: {} (or {"source.organizeImports": true} for Go).
 622    #[settings_ui(skip)]
 623    pub code_actions_on_format: Option<HashMap<String, bool>>,
 624    /// Whether to perform linked edits of associated ranges, if the language server supports it.
 625    /// For example, when editing opening <html> tag, the contents of the closing </html> tag will be edited as well.
 626    ///
 627    /// Default: true
 628    pub linked_edits: Option<bool>,
 629    /// Whether indentation should be adjusted based on the context whilst typing.
 630    ///
 631    /// Default: true
 632    pub auto_indent: Option<bool>,
 633    /// Whether indentation of pasted content should be adjusted based on the context.
 634    ///
 635    /// Default: true
 636    pub auto_indent_on_paste: Option<bool>,
 637    /// Task configuration for this language.
 638    ///
 639    /// Default: {}
 640    pub tasks: Option<LanguageTaskConfig>,
 641    /// Whether to pop the completions menu while typing in an editor without
 642    /// explicitly requesting it.
 643    ///
 644    /// Default: true
 645    pub show_completions_on_input: Option<bool>,
 646    /// Whether to display inline and alongside documentation for items in the
 647    /// completions menu.
 648    ///
 649    /// Default: true
 650    pub show_completion_documentation: Option<bool>,
 651    /// Controls how completions are processed for this language.
 652    pub completions: Option<CompletionSettings>,
 653    /// Preferred debuggers for this language.
 654    ///
 655    /// Default: []
 656    #[settings_ui(skip)]
 657    pub debuggers: Option<Vec<String>>,
 658}
 659
 660/// The behavior of `editor::Rewrap`.
 661#[derive(
 662    Debug, PartialEq, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, SettingsUi,
 663)]
 664#[serde(rename_all = "snake_case")]
 665pub enum RewrapBehavior {
 666    /// Only rewrap within comments.
 667    #[default]
 668    InComments,
 669    /// Only rewrap within the current selection(s).
 670    InSelections,
 671    /// Allow rewrapping anywhere.
 672    Anywhere,
 673}
 674
 675/// The contents of the edit prediction settings.
 676#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, SettingsUi)]
 677pub struct EditPredictionSettingsContent {
 678    /// A list of globs representing files that edit predictions should be disabled for.
 679    /// This list adds to a pre-existing, sensible default set of globs.
 680    /// Any additional ones you add are combined with them.
 681    #[serde(default)]
 682    #[settings_ui(skip)]
 683    pub disabled_globs: Option<Vec<String>>,
 684    /// The mode used to display edit predictions in the buffer.
 685    /// Provider support required.
 686    #[serde(default)]
 687    pub mode: EditPredictionsMode,
 688    /// Settings specific to GitHub Copilot.
 689    #[serde(default)]
 690    pub copilot: CopilotSettingsContent,
 691    /// Whether edit predictions are enabled in the assistant prompt editor.
 692    /// This has no effect if globally disabled.
 693    #[serde(default = "default_true")]
 694    pub enabled_in_text_threads: bool,
 695}
 696
 697#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, SettingsUi)]
 698pub struct CopilotSettingsContent {
 699    /// HTTP/HTTPS proxy to use for Copilot.
 700    ///
 701    /// Default: none
 702    #[serde(default)]
 703    #[settings_ui(skip)]
 704    pub proxy: Option<String>,
 705    /// Disable certificate verification for the proxy (not recommended).
 706    ///
 707    /// Default: false
 708    #[serde(default)]
 709    pub proxy_no_verify: Option<bool>,
 710    /// Enterprise URI for Copilot.
 711    ///
 712    /// Default: none
 713    #[serde(default)]
 714    #[settings_ui(skip)]
 715    pub enterprise_uri: Option<String>,
 716}
 717
 718/// The settings for enabling/disabling features.
 719#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema, SettingsUi)]
 720#[serde(rename_all = "snake_case")]
 721#[settings_ui(group = "Features")]
 722pub struct FeaturesContent {
 723    /// Determines which edit prediction provider to use.
 724    pub edit_prediction_provider: Option<EditPredictionProvider>,
 725}
 726
 727/// Controls the soft-wrapping behavior in the editor.
 728#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, SettingsUi)]
 729#[serde(rename_all = "snake_case")]
 730pub enum SoftWrap {
 731    /// Prefer a single line generally, unless an overly long line is encountered.
 732    None,
 733    /// Deprecated: use None instead. Left to avoid breaking existing users' configs.
 734    /// Prefer a single line generally, unless an overly long line is encountered.
 735    PreferLine,
 736    /// Soft wrap lines that exceed the editor width.
 737    EditorWidth,
 738    /// Soft wrap lines at the preferred line length.
 739    PreferredLineLength,
 740    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
 741    Bounded,
 742}
 743
 744/// Controls the behavior of formatting files when they are saved.
 745#[derive(Debug, Clone, PartialEq, Eq, SettingsUi)]
 746pub enum FormatOnSave {
 747    /// Files should be formatted on save.
 748    On,
 749    /// Files should not be formatted on save.
 750    Off,
 751    List(FormatterList),
 752}
 753
 754impl JsonSchema for FormatOnSave {
 755    fn schema_name() -> Cow<'static, str> {
 756        "OnSaveFormatter".into()
 757    }
 758
 759    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
 760        let formatter_schema = Formatter::json_schema(generator);
 761
 762        json_schema!({
 763            "oneOf": [
 764                {
 765                    "type": "array",
 766                    "items": formatter_schema
 767                },
 768                {
 769                    "type": "string",
 770                    "enum": ["on", "off", "language_server"]
 771                },
 772                formatter_schema
 773            ]
 774        })
 775    }
 776}
 777
 778impl Serialize for FormatOnSave {
 779    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
 780    where
 781        S: serde::Serializer,
 782    {
 783        match self {
 784            Self::On => serializer.serialize_str("on"),
 785            Self::Off => serializer.serialize_str("off"),
 786            Self::List(list) => list.serialize(serializer),
 787        }
 788    }
 789}
 790
 791impl<'de> Deserialize<'de> for FormatOnSave {
 792    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 793    where
 794        D: Deserializer<'de>,
 795    {
 796        struct FormatDeserializer;
 797
 798        impl<'d> Visitor<'d> for FormatDeserializer {
 799            type Value = FormatOnSave;
 800
 801            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
 802                formatter.write_str("a valid on-save formatter kind")
 803            }
 804            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
 805            where
 806                E: serde::de::Error,
 807            {
 808                if v == "on" {
 809                    Ok(Self::Value::On)
 810                } else if v == "off" {
 811                    Ok(Self::Value::Off)
 812                } else if v == "language_server" {
 813                    Ok(Self::Value::List(FormatterList::Single(
 814                        Formatter::LanguageServer { name: None },
 815                    )))
 816                } else {
 817                    let ret: Result<FormatterList, _> =
 818                        Deserialize::deserialize(v.into_deserializer());
 819                    ret.map(Self::Value::List)
 820                }
 821            }
 822            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
 823            where
 824                A: MapAccess<'d>,
 825            {
 826                let ret: Result<FormatterList, _> =
 827                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
 828                ret.map(Self::Value::List)
 829            }
 830            fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
 831            where
 832                A: SeqAccess<'d>,
 833            {
 834                let ret: Result<FormatterList, _> =
 835                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
 836                ret.map(Self::Value::List)
 837            }
 838        }
 839        deserializer.deserialize_any(FormatDeserializer)
 840    }
 841}
 842
 843/// Controls how whitespace should be displayedin the editor.
 844#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, SettingsUi)]
 845#[serde(rename_all = "snake_case")]
 846pub enum ShowWhitespaceSetting {
 847    /// Draw whitespace only for the selected text.
 848    Selection,
 849    /// Do not draw any tabs or spaces.
 850    None,
 851    /// Draw all invisible symbols.
 852    All,
 853    /// Draw whitespaces at boundaries only.
 854    ///
 855    /// For a whitespace to be on a boundary, any of the following conditions need to be met:
 856    /// - It is a tab
 857    /// - It is adjacent to an edge (start or end)
 858    /// - It is adjacent to a whitespace (left or right)
 859    Boundary,
 860    /// Draw whitespaces only after non-whitespace characters.
 861    Trailing,
 862}
 863
 864#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, SettingsUi)]
 865pub struct WhitespaceMap {
 866    #[serde(default)]
 867    pub space: Option<String>,
 868    #[serde(default)]
 869    pub tab: Option<String>,
 870}
 871
 872impl WhitespaceMap {
 873    pub fn space(&self) -> SharedString {
 874        self.space
 875            .as_ref()
 876            .map_or_else(|| SharedString::from(""), |s| SharedString::from(s))
 877    }
 878
 879    pub fn tab(&self) -> SharedString {
 880        self.tab
 881            .as_ref()
 882            .map_or_else(|| SharedString::from(""), |s| SharedString::from(s))
 883    }
 884}
 885
 886/// Controls which formatter should be used when formatting code.
 887#[derive(Clone, Debug, Default, PartialEq, Eq, SettingsUi)]
 888pub enum SelectedFormatter {
 889    /// Format files using Zed's Prettier integration (if applicable),
 890    /// or falling back to formatting via language server.
 891    #[default]
 892    Auto,
 893    List(FormatterList),
 894}
 895
 896impl JsonSchema for SelectedFormatter {
 897    fn schema_name() -> Cow<'static, str> {
 898        "Formatter".into()
 899    }
 900
 901    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
 902        let formatter_schema = Formatter::json_schema(generator);
 903
 904        json_schema!({
 905            "oneOf": [
 906                {
 907                    "type": "array",
 908                    "items": formatter_schema
 909                },
 910                {
 911                    "type": "string",
 912                    "enum": ["auto", "language_server"]
 913                },
 914                formatter_schema
 915            ]
 916        })
 917    }
 918}
 919
 920impl Serialize for SelectedFormatter {
 921    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
 922    where
 923        S: serde::Serializer,
 924    {
 925        match self {
 926            SelectedFormatter::Auto => serializer.serialize_str("auto"),
 927            SelectedFormatter::List(list) => list.serialize(serializer),
 928        }
 929    }
 930}
 931
 932impl<'de> Deserialize<'de> for SelectedFormatter {
 933    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 934    where
 935        D: Deserializer<'de>,
 936    {
 937        struct FormatDeserializer;
 938
 939        impl<'d> Visitor<'d> for FormatDeserializer {
 940            type Value = SelectedFormatter;
 941
 942            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
 943                formatter.write_str("a valid formatter kind")
 944            }
 945            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
 946            where
 947                E: serde::de::Error,
 948            {
 949                if v == "auto" {
 950                    Ok(Self::Value::Auto)
 951                } else if v == "language_server" {
 952                    Ok(Self::Value::List(FormatterList::Single(
 953                        Formatter::LanguageServer { name: None },
 954                    )))
 955                } else {
 956                    let ret: Result<FormatterList, _> =
 957                        Deserialize::deserialize(v.into_deserializer());
 958                    ret.map(SelectedFormatter::List)
 959                }
 960            }
 961            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
 962            where
 963                A: MapAccess<'d>,
 964            {
 965                let ret: Result<FormatterList, _> =
 966                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
 967                ret.map(SelectedFormatter::List)
 968            }
 969            fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
 970            where
 971                A: SeqAccess<'d>,
 972            {
 973                let ret: Result<FormatterList, _> =
 974                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
 975                ret.map(SelectedFormatter::List)
 976            }
 977        }
 978        deserializer.deserialize_any(FormatDeserializer)
 979    }
 980}
 981
 982/// Controls which formatters should be used when formatting code.
 983#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, SettingsUi)]
 984#[serde(untagged)]
 985pub enum FormatterList {
 986    Single(Formatter),
 987    Vec(#[settings_ui(skip)] Vec<Formatter>),
 988}
 989
 990impl Default for FormatterList {
 991    fn default() -> Self {
 992        Self::Single(Formatter::default())
 993    }
 994}
 995
 996impl AsRef<[Formatter]> for FormatterList {
 997    fn as_ref(&self) -> &[Formatter] {
 998        match &self {
 999            Self::Single(single) => slice::from_ref(single),
1000            Self::Vec(v) => v,
1001        }
1002    }
1003}
1004
1005/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
1006#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, SettingsUi)]
1007#[serde(rename_all = "snake_case")]
1008pub enum Formatter {
1009    /// Format code using the current language server.
1010    LanguageServer {
1011        #[settings_ui(skip)]
1012        name: Option<String>,
1013    },
1014    /// Format code using Zed's Prettier integration.
1015    #[default]
1016    Prettier,
1017    /// Format code using an external command.
1018    External {
1019        /// The external program to run.
1020        #[settings_ui(skip)]
1021        command: Arc<str>,
1022        /// The arguments to pass to the program.
1023        #[settings_ui(skip)]
1024        arguments: Option<Arc<[String]>>,
1025    },
1026    /// Files should be formatted using code actions executed by language servers.
1027    CodeActions(#[settings_ui(skip)] HashMap<String, bool>),
1028}
1029
1030/// The settings for indent guides.
1031#[derive(
1032    Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, SettingsUi,
1033)]
1034pub struct IndentGuideSettings {
1035    /// Whether to display indent guides in the editor.
1036    ///
1037    /// Default: true
1038    #[serde(default = "default_true")]
1039    pub enabled: bool,
1040    /// The width of the indent guides in pixels, between 1 and 10.
1041    ///
1042    /// Default: 1
1043    #[serde(default = "line_width")]
1044    pub line_width: u32,
1045    /// The width of the active indent guide in pixels, between 1 and 10.
1046    ///
1047    /// Default: 1
1048    #[serde(default = "active_line_width")]
1049    pub active_line_width: u32,
1050    /// Determines how indent guides are colored.
1051    ///
1052    /// Default: Fixed
1053    #[serde(default)]
1054    pub coloring: IndentGuideColoring,
1055    /// Determines how indent guide backgrounds are colored.
1056    ///
1057    /// Default: Disabled
1058    #[serde(default)]
1059    pub background_coloring: IndentGuideBackgroundColoring,
1060}
1061
1062fn line_width() -> u32 {
1063    1
1064}
1065
1066fn active_line_width() -> u32 {
1067    line_width()
1068}
1069
1070/// Determines how indent guides are colored.
1071#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1072#[serde(rename_all = "snake_case")]
1073pub enum IndentGuideColoring {
1074    /// Do not render any lines for indent guides.
1075    Disabled,
1076    /// Use the same color for all indentation levels.
1077    #[default]
1078    Fixed,
1079    /// Use a different color for each indentation level.
1080    IndentAware,
1081}
1082
1083/// Determines how indent guide backgrounds are colored.
1084#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1085#[serde(rename_all = "snake_case")]
1086pub enum IndentGuideBackgroundColoring {
1087    /// Do not render any background for indent guides.
1088    #[default]
1089    Disabled,
1090    /// Use a different color for each indentation level.
1091    IndentAware,
1092}
1093
1094/// The settings for inlay hints.
1095#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, SettingsUi)]
1096pub struct InlayHintSettings {
1097    /// Global switch to toggle hints on and off.
1098    ///
1099    /// Default: false
1100    #[serde(default)]
1101    pub enabled: bool,
1102    /// Global switch to toggle inline values on and off when debugging.
1103    ///
1104    /// Default: true
1105    #[serde(default = "default_true")]
1106    pub show_value_hints: bool,
1107    /// Whether type hints should be shown.
1108    ///
1109    /// Default: true
1110    #[serde(default = "default_true")]
1111    pub show_type_hints: bool,
1112    /// Whether parameter hints should be shown.
1113    ///
1114    /// Default: true
1115    #[serde(default = "default_true")]
1116    pub show_parameter_hints: bool,
1117    /// Whether other hints should be shown.
1118    ///
1119    /// Default: true
1120    #[serde(default = "default_true")]
1121    pub show_other_hints: bool,
1122    /// Whether to show a background for inlay hints.
1123    ///
1124    /// If set to `true`, the background will use the `hint.background` color
1125    /// from the current theme.
1126    ///
1127    /// Default: false
1128    #[serde(default)]
1129    pub show_background: bool,
1130    /// Whether or not to debounce inlay hints updates after buffer edits.
1131    ///
1132    /// Set to 0 to disable debouncing.
1133    ///
1134    /// Default: 700
1135    #[serde(default = "edit_debounce_ms")]
1136    pub edit_debounce_ms: u64,
1137    /// Whether or not to debounce inlay hints updates after buffer scrolls.
1138    ///
1139    /// Set to 0 to disable debouncing.
1140    ///
1141    /// Default: 50
1142    #[serde(default = "scroll_debounce_ms")]
1143    pub scroll_debounce_ms: u64,
1144    /// Toggles inlay hints (hides or shows) when the user presses the modifiers specified.
1145    /// If only a subset of the modifiers specified is pressed, hints are not toggled.
1146    /// If no modifiers are specified, this is equivalent to `None`.
1147    ///
1148    /// Default: None
1149    #[serde(default)]
1150    pub toggle_on_modifiers_press: Option<Modifiers>,
1151}
1152
1153fn edit_debounce_ms() -> u64 {
1154    700
1155}
1156
1157fn scroll_debounce_ms() -> u64 {
1158    50
1159}
1160
1161/// The task settings for a particular language.
1162#[derive(Debug, Clone, Deserialize, PartialEq, Serialize, JsonSchema, SettingsUi)]
1163pub struct LanguageTaskConfig {
1164    /// Extra task variables to set for a particular language.
1165    #[serde(default)]
1166    pub variables: HashMap<String, String>,
1167    #[serde(default = "default_true")]
1168    pub enabled: bool,
1169    /// Use LSP tasks over Zed language extension ones.
1170    /// If no LSP tasks are returned due to error/timeout or regular execution,
1171    /// Zed language extension tasks will be used instead.
1172    ///
1173    /// Other Zed tasks will still be shown:
1174    /// * Zed task from either of the task config file
1175    /// * Zed task from history (e.g. one-off task was spawned before)
1176    #[serde(default = "default_true")]
1177    pub prefer_lsp: bool,
1178}
1179
1180impl InlayHintSettings {
1181    /// Returns the kinds of inlay hints that are enabled based on the settings.
1182    pub fn enabled_inlay_hint_kinds(&self) -> HashSet<Option<InlayHintKind>> {
1183        let mut kinds = HashSet::default();
1184        if self.show_type_hints {
1185            kinds.insert(Some(InlayHintKind::Type));
1186        }
1187        if self.show_parameter_hints {
1188            kinds.insert(Some(InlayHintKind::Parameter));
1189        }
1190        if self.show_other_hints {
1191            kinds.insert(None);
1192        }
1193        kinds
1194    }
1195}
1196
1197impl AllLanguageSettings {
1198    /// Returns the [`LanguageSettings`] for the language with the specified name.
1199    pub fn language<'a>(
1200        &'a self,
1201        location: Option<SettingsLocation<'a>>,
1202        language_name: Option<&LanguageName>,
1203        cx: &'a App,
1204    ) -> Cow<'a, LanguageSettings> {
1205        let settings = language_name
1206            .and_then(|name| self.languages.get(name))
1207            .unwrap_or(&self.defaults);
1208
1209        let editorconfig_properties = location.and_then(|location| {
1210            cx.global::<SettingsStore>()
1211                .editorconfig_properties(location.worktree_id, location.path)
1212        });
1213        if let Some(editorconfig_properties) = editorconfig_properties {
1214            let mut settings = settings.clone();
1215            merge_with_editorconfig(&mut settings, &editorconfig_properties);
1216            Cow::Owned(settings)
1217        } else {
1218            Cow::Borrowed(settings)
1219        }
1220    }
1221
1222    /// Returns whether edit predictions are enabled for the given path.
1223    pub fn edit_predictions_enabled_for_file(&self, file: &Arc<dyn File>, cx: &App) -> bool {
1224        self.edit_predictions.enabled_for_file(file, cx)
1225    }
1226
1227    /// Returns whether edit predictions are enabled for the given language and path.
1228    pub fn show_edit_predictions(&self, language: Option<&Arc<Language>>, cx: &App) -> bool {
1229        self.language(None, language.map(|l| l.name()).as_ref(), cx)
1230            .show_edit_predictions
1231    }
1232
1233    /// Returns the edit predictions preview mode for the given language and path.
1234    pub fn edit_predictions_mode(&self) -> EditPredictionsMode {
1235        self.edit_predictions.mode
1236    }
1237}
1238
1239fn merge_with_editorconfig(settings: &mut LanguageSettings, cfg: &EditorconfigProperties) {
1240    let preferred_line_length = cfg.get::<MaxLineLen>().ok().and_then(|v| match v {
1241        MaxLineLen::Value(u) => Some(u as u32),
1242        MaxLineLen::Off => None,
1243    });
1244    let tab_size = cfg.get::<IndentSize>().ok().and_then(|v| match v {
1245        IndentSize::Value(u) => NonZeroU32::new(u as u32),
1246        IndentSize::UseTabWidth => cfg.get::<TabWidth>().ok().and_then(|w| match w {
1247            TabWidth::Value(u) => NonZeroU32::new(u as u32),
1248        }),
1249    });
1250    let hard_tabs = cfg
1251        .get::<IndentStyle>()
1252        .map(|v| v.eq(&IndentStyle::Tabs))
1253        .ok();
1254    let ensure_final_newline_on_save = cfg
1255        .get::<FinalNewline>()
1256        .map(|v| match v {
1257            FinalNewline::Value(b) => b,
1258        })
1259        .ok();
1260    let remove_trailing_whitespace_on_save = cfg
1261        .get::<TrimTrailingWs>()
1262        .map(|v| match v {
1263            TrimTrailingWs::Value(b) => b,
1264        })
1265        .ok();
1266    fn merge<T>(target: &mut T, value: Option<T>) {
1267        if let Some(value) = value {
1268            *target = value;
1269        }
1270    }
1271    merge(&mut settings.preferred_line_length, preferred_line_length);
1272    merge(&mut settings.tab_size, tab_size);
1273    merge(&mut settings.hard_tabs, hard_tabs);
1274    merge(
1275        &mut settings.remove_trailing_whitespace_on_save,
1276        remove_trailing_whitespace_on_save,
1277    );
1278    merge(
1279        &mut settings.ensure_final_newline_on_save,
1280        ensure_final_newline_on_save,
1281    );
1282}
1283
1284/// The kind of an inlay hint.
1285#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1286pub enum InlayHintKind {
1287    /// An inlay hint for a type.
1288    Type,
1289    /// An inlay hint for a parameter.
1290    Parameter,
1291}
1292
1293impl InlayHintKind {
1294    /// Returns the [`InlayHintKind`] from the given name.
1295    ///
1296    /// Returns `None` if `name` does not match any of the expected
1297    /// string representations.
1298    pub fn from_name(name: &str) -> Option<Self> {
1299        match name {
1300            "type" => Some(InlayHintKind::Type),
1301            "parameter" => Some(InlayHintKind::Parameter),
1302            _ => None,
1303        }
1304    }
1305
1306    /// Returns the name of this [`InlayHintKind`].
1307    pub fn name(&self) -> &'static str {
1308        match self {
1309            InlayHintKind::Type => "type",
1310            InlayHintKind::Parameter => "parameter",
1311        }
1312    }
1313}
1314
1315impl settings::Settings for AllLanguageSettings {
1316    type FileContent = AllLanguageSettingsContent;
1317
1318    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1319        let default_value = sources.default;
1320
1321        // A default is provided for all settings.
1322        let mut defaults: LanguageSettings =
1323            serde_json::from_value(serde_json::to_value(&default_value.defaults)?)?;
1324
1325        let mut languages = HashMap::default();
1326        for (language_name, settings) in &default_value.languages.0 {
1327            let mut language_settings = defaults.clone();
1328            merge_settings(&mut language_settings, settings);
1329            languages.insert(language_name.clone(), language_settings);
1330        }
1331
1332        let mut edit_prediction_provider = default_value
1333            .features
1334            .as_ref()
1335            .and_then(|f| f.edit_prediction_provider);
1336        let mut edit_predictions_mode = default_value
1337            .edit_predictions
1338            .as_ref()
1339            .map(|edit_predictions| edit_predictions.mode)
1340            .ok_or_else(Self::missing_default)?;
1341
1342        let mut completion_globs: HashSet<&String> = default_value
1343            .edit_predictions
1344            .as_ref()
1345            .and_then(|c| c.disabled_globs.as_ref())
1346            .map(|globs| globs.iter().collect())
1347            .ok_or_else(Self::missing_default)?;
1348
1349        let mut copilot_settings = default_value
1350            .edit_predictions
1351            .as_ref()
1352            .map(|settings| CopilotSettings {
1353                proxy: settings.copilot.proxy.clone(),
1354                proxy_no_verify: settings.copilot.proxy_no_verify,
1355                enterprise_uri: settings.copilot.enterprise_uri.clone(),
1356            })
1357            .unwrap_or_default();
1358
1359        let mut enabled_in_text_threads = default_value
1360            .edit_predictions
1361            .as_ref()
1362            .map(|settings| settings.enabled_in_text_threads)
1363            .unwrap_or(true);
1364
1365        let mut file_types: FxHashMap<Arc<str>, GlobSet> = FxHashMap::default();
1366
1367        for (language, patterns) in &default_value.file_types {
1368            let mut builder = GlobSetBuilder::new();
1369
1370            for pattern in patterns {
1371                builder.add(Glob::new(pattern)?);
1372            }
1373
1374            file_types.insert(language.clone(), builder.build()?);
1375        }
1376
1377        for user_settings in sources.customizations() {
1378            if let Some(provider) = user_settings
1379                .features
1380                .as_ref()
1381                .and_then(|f| f.edit_prediction_provider)
1382            {
1383                edit_prediction_provider = Some(provider);
1384            }
1385
1386            if let Some(edit_predictions) = user_settings.edit_predictions.as_ref() {
1387                edit_predictions_mode = edit_predictions.mode;
1388                enabled_in_text_threads = edit_predictions.enabled_in_text_threads;
1389
1390                if let Some(disabled_globs) = edit_predictions.disabled_globs.as_ref() {
1391                    completion_globs.extend(disabled_globs.iter());
1392                }
1393            }
1394
1395            if let Some(proxy) = user_settings
1396                .edit_predictions
1397                .as_ref()
1398                .and_then(|settings| settings.copilot.proxy.clone())
1399            {
1400                copilot_settings.proxy = Some(proxy);
1401            }
1402
1403            if let Some(proxy_no_verify) = user_settings
1404                .edit_predictions
1405                .as_ref()
1406                .and_then(|settings| settings.copilot.proxy_no_verify)
1407            {
1408                copilot_settings.proxy_no_verify = Some(proxy_no_verify);
1409            }
1410
1411            if let Some(enterprise_uri) = user_settings
1412                .edit_predictions
1413                .as_ref()
1414                .and_then(|settings| settings.copilot.enterprise_uri.clone())
1415            {
1416                copilot_settings.enterprise_uri = Some(enterprise_uri);
1417            }
1418
1419            // A user's global settings override the default global settings and
1420            // all default language-specific settings.
1421            merge_settings(&mut defaults, &user_settings.defaults);
1422            for language_settings in languages.values_mut() {
1423                merge_settings(language_settings, &user_settings.defaults);
1424            }
1425
1426            // A user's language-specific settings override default language-specific settings.
1427            for (language_name, user_language_settings) in &user_settings.languages.0 {
1428                merge_settings(
1429                    languages
1430                        .entry(language_name.clone())
1431                        .or_insert_with(|| defaults.clone()),
1432                    user_language_settings,
1433                );
1434            }
1435
1436            for (language, patterns) in &user_settings.file_types {
1437                let mut builder = GlobSetBuilder::new();
1438
1439                let default_value = default_value.file_types.get(&language.clone());
1440
1441                // Merge the default value with the user's value.
1442                if let Some(patterns) = default_value {
1443                    for pattern in patterns {
1444                        builder.add(Glob::new(pattern)?);
1445                    }
1446                }
1447
1448                for pattern in patterns {
1449                    builder.add(Glob::new(pattern)?);
1450                }
1451
1452                file_types.insert(language.clone(), builder.build()?);
1453            }
1454        }
1455
1456        Ok(Self {
1457            edit_predictions: EditPredictionSettings {
1458                provider: if let Some(provider) = edit_prediction_provider {
1459                    provider
1460                } else {
1461                    EditPredictionProvider::None
1462                },
1463                disabled_globs: completion_globs
1464                    .iter()
1465                    .filter_map(|g| {
1466                        let expanded_g = shellexpand::tilde(g).into_owned();
1467                        Some(DisabledGlob {
1468                            matcher: globset::Glob::new(&expanded_g).ok()?.compile_matcher(),
1469                            is_absolute: Path::new(&expanded_g).is_absolute(),
1470                        })
1471                    })
1472                    .collect(),
1473                mode: edit_predictions_mode,
1474                copilot: copilot_settings,
1475                enabled_in_text_threads,
1476            },
1477            defaults,
1478            languages,
1479            file_types,
1480        })
1481    }
1482
1483    fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
1484        let d = &mut current.defaults;
1485        if let Some(size) = vscode
1486            .read_value("editor.tabSize")
1487            .and_then(|v| v.as_u64())
1488            .and_then(|n| NonZeroU32::new(n as u32))
1489        {
1490            d.tab_size = Some(size);
1491        }
1492        if let Some(v) = vscode.read_bool("editor.insertSpaces") {
1493            d.hard_tabs = Some(!v);
1494        }
1495
1496        vscode.enum_setting("editor.wordWrap", &mut d.soft_wrap, |s| match s {
1497            "on" => Some(SoftWrap::EditorWidth),
1498            "wordWrapColumn" => Some(SoftWrap::PreferLine),
1499            "bounded" => Some(SoftWrap::Bounded),
1500            "off" => Some(SoftWrap::None),
1501            _ => None,
1502        });
1503        vscode.u32_setting("editor.wordWrapColumn", &mut d.preferred_line_length);
1504
1505        if let Some(arr) = vscode
1506            .read_value("editor.rulers")
1507            .and_then(|v| v.as_array())
1508            .map(|v| v.iter().map(|n| n.as_u64().map(|n| n as usize)).collect())
1509        {
1510            d.wrap_guides = arr;
1511        }
1512        if let Some(b) = vscode.read_bool("editor.guides.indentation") {
1513            if let Some(guide_settings) = d.indent_guides.as_mut() {
1514                guide_settings.enabled = b;
1515            } else {
1516                d.indent_guides = Some(IndentGuideSettings {
1517                    enabled: b,
1518                    ..Default::default()
1519                });
1520            }
1521        }
1522
1523        if let Some(b) = vscode.read_bool("editor.guides.formatOnSave") {
1524            d.format_on_save = Some(if b {
1525                FormatOnSave::On
1526            } else {
1527                FormatOnSave::Off
1528            });
1529        }
1530        vscode.bool_setting(
1531            "editor.trimAutoWhitespace",
1532            &mut d.remove_trailing_whitespace_on_save,
1533        );
1534        vscode.bool_setting(
1535            "files.insertFinalNewline",
1536            &mut d.ensure_final_newline_on_save,
1537        );
1538        vscode.bool_setting("editor.inlineSuggest.enabled", &mut d.show_edit_predictions);
1539        vscode.enum_setting("editor.renderWhitespace", &mut d.show_whitespaces, |s| {
1540            Some(match s {
1541                "boundary" => ShowWhitespaceSetting::Boundary,
1542                "trailing" => ShowWhitespaceSetting::Trailing,
1543                "selection" => ShowWhitespaceSetting::Selection,
1544                "all" => ShowWhitespaceSetting::All,
1545                _ => ShowWhitespaceSetting::None,
1546            })
1547        });
1548        vscode.enum_setting(
1549            "editor.autoSurround",
1550            &mut d.use_auto_surround,
1551            |s| match s {
1552                "languageDefined" | "quotes" | "brackets" => Some(true),
1553                "never" => Some(false),
1554                _ => None,
1555            },
1556        );
1557        vscode.bool_setting("editor.formatOnType", &mut d.use_on_type_format);
1558        vscode.bool_setting("editor.linkedEditing", &mut d.linked_edits);
1559        vscode.bool_setting("editor.formatOnPaste", &mut d.auto_indent_on_paste);
1560        vscode.bool_setting(
1561            "editor.suggestOnTriggerCharacters",
1562            &mut d.show_completions_on_input,
1563        );
1564        if let Some(b) = vscode.read_bool("editor.suggest.showWords") {
1565            let mode = if b {
1566                WordsCompletionMode::Enabled
1567            } else {
1568                WordsCompletionMode::Disabled
1569            };
1570            if let Some(completion_settings) = d.completions.as_mut() {
1571                completion_settings.words = mode;
1572            } else {
1573                d.completions = Some(CompletionSettings {
1574                    words: mode,
1575                    words_min_length: 3,
1576                    lsp: true,
1577                    lsp_fetch_timeout_ms: 0,
1578                    lsp_insert_mode: LspInsertMode::ReplaceSuffix,
1579                });
1580            }
1581        }
1582        // TODO: pull ^ out into helper and reuse for per-language settings
1583
1584        // vscodes file association map is inverted from ours, so we flip the mapping before merging
1585        let mut associations: HashMap<Arc<str>, Vec<String>> = HashMap::default();
1586        if let Some(map) = vscode
1587            .read_value("files.associations")
1588            .and_then(|v| v.as_object())
1589        {
1590            for (k, v) in map {
1591                let Some(v) = v.as_str() else { continue };
1592                associations.entry(v.into()).or_default().push(k.clone());
1593            }
1594        }
1595
1596        // TODO: do we want to merge imported globs per filetype? for now we'll just replace
1597        current.file_types.extend(associations);
1598
1599        // cursor global ignore list applies to cursor-tab, so transfer it to edit_predictions.disabled_globs
1600        if let Some(disabled_globs) = vscode
1601            .read_value("cursor.general.globalCursorIgnoreList")
1602            .and_then(|v| v.as_array())
1603        {
1604            current
1605                .edit_predictions
1606                .get_or_insert_default()
1607                .disabled_globs
1608                .get_or_insert_default()
1609                .extend(
1610                    disabled_globs
1611                        .iter()
1612                        .filter_map(|glob| glob.as_str())
1613                        .map(|s| s.to_string()),
1614                );
1615        }
1616    }
1617}
1618
1619fn merge_settings(settings: &mut LanguageSettings, src: &LanguageSettingsContent) {
1620    fn merge<T>(target: &mut T, value: Option<T>) {
1621        if let Some(value) = value {
1622            *target = value;
1623        }
1624    }
1625
1626    merge(&mut settings.tab_size, src.tab_size);
1627    settings.tab_size = settings
1628        .tab_size
1629        .clamp(NonZeroU32::new(1).unwrap(), NonZeroU32::new(16).unwrap());
1630
1631    merge(&mut settings.hard_tabs, src.hard_tabs);
1632    merge(&mut settings.soft_wrap, src.soft_wrap);
1633    merge(&mut settings.use_autoclose, src.use_autoclose);
1634    merge(&mut settings.use_auto_surround, src.use_auto_surround);
1635    merge(&mut settings.use_on_type_format, src.use_on_type_format);
1636    merge(&mut settings.auto_indent, src.auto_indent);
1637    merge(&mut settings.auto_indent_on_paste, src.auto_indent_on_paste);
1638    merge(
1639        &mut settings.always_treat_brackets_as_autoclosed,
1640        src.always_treat_brackets_as_autoclosed,
1641    );
1642    merge(&mut settings.show_wrap_guides, src.show_wrap_guides);
1643    merge(&mut settings.wrap_guides, src.wrap_guides.clone());
1644    merge(&mut settings.indent_guides, src.indent_guides);
1645    merge(
1646        &mut settings.code_actions_on_format,
1647        src.code_actions_on_format.clone(),
1648    );
1649    merge(&mut settings.linked_edits, src.linked_edits);
1650    merge(&mut settings.tasks, src.tasks.clone());
1651
1652    merge(
1653        &mut settings.preferred_line_length,
1654        src.preferred_line_length,
1655    );
1656    merge(&mut settings.formatter, src.formatter.clone());
1657    merge(&mut settings.prettier, src.prettier.clone());
1658    merge(
1659        &mut settings.jsx_tag_auto_close,
1660        src.jsx_tag_auto_close.clone(),
1661    );
1662    merge(&mut settings.format_on_save, src.format_on_save.clone());
1663    merge(
1664        &mut settings.remove_trailing_whitespace_on_save,
1665        src.remove_trailing_whitespace_on_save,
1666    );
1667    merge(
1668        &mut settings.ensure_final_newline_on_save,
1669        src.ensure_final_newline_on_save,
1670    );
1671    merge(
1672        &mut settings.enable_language_server,
1673        src.enable_language_server,
1674    );
1675    merge(&mut settings.language_servers, src.language_servers.clone());
1676    merge(&mut settings.allow_rewrap, src.allow_rewrap);
1677    merge(
1678        &mut settings.show_edit_predictions,
1679        src.show_edit_predictions,
1680    );
1681    merge(
1682        &mut settings.edit_predictions_disabled_in,
1683        src.edit_predictions_disabled_in.clone(),
1684    );
1685    merge(&mut settings.show_whitespaces, src.show_whitespaces);
1686    merge(&mut settings.whitespace_map, src.whitespace_map.clone());
1687    merge(
1688        &mut settings.extend_comment_on_newline,
1689        src.extend_comment_on_newline,
1690    );
1691    merge(&mut settings.inlay_hints, src.inlay_hints);
1692    merge(
1693        &mut settings.show_completions_on_input,
1694        src.show_completions_on_input,
1695    );
1696    merge(
1697        &mut settings.show_completion_documentation,
1698        src.show_completion_documentation,
1699    );
1700    merge(&mut settings.completions, src.completions);
1701}
1702
1703/// Allows to enable/disable formatting with Prettier
1704/// and configure default Prettier, used when no project-level Prettier installation is found.
1705/// Prettier formatting is disabled by default.
1706#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, SettingsUi)]
1707pub struct PrettierSettings {
1708    /// Enables or disables formatting with Prettier for a given language.
1709    #[serde(default)]
1710    pub allowed: bool,
1711
1712    /// Forces Prettier integration to use a specific parser name when formatting files with the language.
1713    #[serde(default)]
1714    pub parser: Option<String>,
1715
1716    /// Forces Prettier integration to use specific plugins when formatting files with the language.
1717    /// The default Prettier will be installed with these plugins.
1718    #[serde(default)]
1719    #[settings_ui(skip)]
1720    pub plugins: HashSet<String>,
1721
1722    /// Default Prettier options, in the format as in package.json section for Prettier.
1723    /// If project installs Prettier via its package.json, these options will be ignored.
1724    #[serde(flatten)]
1725    #[settings_ui(skip)]
1726    pub options: HashMap<String, serde_json::Value>,
1727}
1728
1729#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, SettingsUi)]
1730pub struct JsxTagAutoCloseSettings {
1731    /// Enables or disables auto-closing of JSX tags.
1732    #[serde(default)]
1733    pub enabled: bool,
1734}
1735
1736#[cfg(test)]
1737mod tests {
1738    use gpui::TestAppContext;
1739
1740    use super::*;
1741
1742    #[test]
1743    fn test_formatter_deserialization() {
1744        let raw_auto = "{\"formatter\": \"auto\"}";
1745        let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
1746        assert_eq!(settings.formatter, Some(SelectedFormatter::Auto));
1747        let raw = "{\"formatter\": \"language_server\"}";
1748        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1749        assert_eq!(
1750            settings.formatter,
1751            Some(SelectedFormatter::List(FormatterList::Single(
1752                Formatter::LanguageServer { name: None }
1753            )))
1754        );
1755        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
1756        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1757        assert_eq!(
1758            settings.formatter,
1759            Some(SelectedFormatter::List(FormatterList::Vec(vec![
1760                Formatter::LanguageServer { name: None }
1761            ])))
1762        );
1763        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"prettier\"]}";
1764        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1765        assert_eq!(
1766            settings.formatter,
1767            Some(SelectedFormatter::List(FormatterList::Vec(vec![
1768                Formatter::LanguageServer { name: None },
1769                Formatter::Prettier
1770            ])))
1771        );
1772    }
1773
1774    #[test]
1775    fn test_formatter_deserialization_invalid() {
1776        let raw_auto = "{\"formatter\": {}}";
1777        let result: Result<LanguageSettingsContent, _> = serde_json::from_str(raw_auto);
1778        assert!(result.is_err());
1779    }
1780
1781    #[gpui::test]
1782    fn test_edit_predictions_enabled_for_file(cx: &mut TestAppContext) {
1783        use crate::TestFile;
1784        use std::path::PathBuf;
1785
1786        let cx = cx.app.borrow_mut();
1787
1788        let build_settings = |globs: &[&str]| -> EditPredictionSettings {
1789            EditPredictionSettings {
1790                disabled_globs: globs
1791                    .iter()
1792                    .map(|glob_str| {
1793                        #[cfg(windows)]
1794                        let glob_str = {
1795                            let mut g = String::new();
1796
1797                            if glob_str.starts_with('/') {
1798                                g.push_str("C:");
1799                            }
1800
1801                            g.push_str(&glob_str.replace('/', "\\"));
1802                            g
1803                        };
1804                        #[cfg(windows)]
1805                        let glob_str = glob_str.as_str();
1806                        let expanded_glob_str = shellexpand::tilde(glob_str).into_owned();
1807                        DisabledGlob {
1808                            matcher: globset::Glob::new(&expanded_glob_str)
1809                                .unwrap()
1810                                .compile_matcher(),
1811                            is_absolute: Path::new(&expanded_glob_str).is_absolute(),
1812                        }
1813                    })
1814                    .collect(),
1815                ..Default::default()
1816            }
1817        };
1818
1819        const WORKTREE_NAME: &str = "project";
1820        let make_test_file = |segments: &[&str]| -> Arc<dyn File> {
1821            let mut path_buf = PathBuf::new();
1822            path_buf.extend(segments);
1823
1824            Arc::new(TestFile {
1825                path: path_buf.as_path().into(),
1826                root_name: WORKTREE_NAME.to_string(),
1827                local_root: Some(PathBuf::from(if cfg!(windows) {
1828                    "C:\\absolute\\"
1829                } else {
1830                    "/absolute/"
1831                })),
1832            })
1833        };
1834
1835        let test_file = make_test_file(&["src", "test", "file.rs"]);
1836
1837        // Test relative globs
1838        let settings = build_settings(&["*.rs"]);
1839        assert!(!settings.enabled_for_file(&test_file, &cx));
1840        let settings = build_settings(&["*.txt"]);
1841        assert!(settings.enabled_for_file(&test_file, &cx));
1842
1843        // Test absolute globs
1844        let settings = build_settings(&["/absolute/**/*.rs"]);
1845        assert!(!settings.enabled_for_file(&test_file, &cx));
1846        let settings = build_settings(&["/other/**/*.rs"]);
1847        assert!(settings.enabled_for_file(&test_file, &cx));
1848
1849        // Test exact path match relative
1850        let settings = build_settings(&["src/test/file.rs"]);
1851        assert!(!settings.enabled_for_file(&test_file, &cx));
1852        let settings = build_settings(&["src/test/otherfile.rs"]);
1853        assert!(settings.enabled_for_file(&test_file, &cx));
1854
1855        // Test exact path match absolute
1856        let settings = build_settings(&[&format!("/absolute/{}/src/test/file.rs", WORKTREE_NAME)]);
1857        assert!(!settings.enabled_for_file(&test_file, &cx));
1858        let settings = build_settings(&["/other/test/otherfile.rs"]);
1859        assert!(settings.enabled_for_file(&test_file, &cx));
1860
1861        // Test * glob
1862        let settings = build_settings(&["*"]);
1863        assert!(!settings.enabled_for_file(&test_file, &cx));
1864        let settings = build_settings(&["*.txt"]);
1865        assert!(settings.enabled_for_file(&test_file, &cx));
1866
1867        // Test **/* glob
1868        let settings = build_settings(&["**/*"]);
1869        assert!(!settings.enabled_for_file(&test_file, &cx));
1870        let settings = build_settings(&["other/**/*"]);
1871        assert!(settings.enabled_for_file(&test_file, &cx));
1872
1873        // Test directory/** glob
1874        let settings = build_settings(&["src/**"]);
1875        assert!(!settings.enabled_for_file(&test_file, &cx));
1876
1877        let test_file_root: Arc<dyn File> = Arc::new(TestFile {
1878            path: PathBuf::from("file.rs").as_path().into(),
1879            root_name: WORKTREE_NAME.to_string(),
1880            local_root: Some(PathBuf::from("/absolute/")),
1881        });
1882        assert!(settings.enabled_for_file(&test_file_root, &cx));
1883
1884        let settings = build_settings(&["other/**"]);
1885        assert!(settings.enabled_for_file(&test_file, &cx));
1886
1887        // Test **/directory/* glob
1888        let settings = build_settings(&["**/test/*"]);
1889        assert!(!settings.enabled_for_file(&test_file, &cx));
1890        let settings = build_settings(&["**/other/*"]);
1891        assert!(settings.enabled_for_file(&test_file, &cx));
1892
1893        // Test multiple globs
1894        let settings = build_settings(&["*.rs", "*.txt", "src/**"]);
1895        assert!(!settings.enabled_for_file(&test_file, &cx));
1896        let settings = build_settings(&["*.txt", "*.md", "other/**"]);
1897        assert!(settings.enabled_for_file(&test_file, &cx));
1898
1899        // Test dot files
1900        let dot_file = make_test_file(&[".config", "settings.json"]);
1901        let settings = build_settings(&[".*/**"]);
1902        assert!(!settings.enabled_for_file(&dot_file, &cx));
1903
1904        let dot_env_file = make_test_file(&[".env"]);
1905        let settings = build_settings(&[".env"]);
1906        assert!(!settings.enabled_for_file(&dot_env_file, &cx));
1907
1908        // Test tilde expansion
1909        let home = shellexpand::tilde("~").into_owned();
1910        let home_file = make_test_file(&[&home, "test.rs"]);
1911        let settings = build_settings(&["~/test.rs"]);
1912        assert!(!settings.enabled_for_file(&home_file, &cx));
1913    }
1914
1915    #[test]
1916    fn test_resolve_language_servers() {
1917        fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
1918            names
1919                .iter()
1920                .copied()
1921                .map(|name| LanguageServerName(name.to_string().into()))
1922                .collect::<Vec<_>>()
1923        }
1924
1925        let available_language_servers = language_server_names(&[
1926            "typescript-language-server",
1927            "biome",
1928            "deno",
1929            "eslint",
1930            "tailwind",
1931        ]);
1932
1933        // A value of just `["..."]` is the same as taking all of the available language servers.
1934        assert_eq!(
1935            LanguageSettings::resolve_language_servers(
1936                &[LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()],
1937                &available_language_servers,
1938            ),
1939            available_language_servers
1940        );
1941
1942        // Referencing one of the available language servers will change its order.
1943        assert_eq!(
1944            LanguageSettings::resolve_language_servers(
1945                &[
1946                    "biome".into(),
1947                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into(),
1948                    "deno".into()
1949                ],
1950                &available_language_servers
1951            ),
1952            language_server_names(&[
1953                "biome",
1954                "typescript-language-server",
1955                "eslint",
1956                "tailwind",
1957                "deno",
1958            ])
1959        );
1960
1961        // Negating an available language server removes it from the list.
1962        assert_eq!(
1963            LanguageSettings::resolve_language_servers(
1964                &[
1965                    "deno".into(),
1966                    "!typescript-language-server".into(),
1967                    "!biome".into(),
1968                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1969                ],
1970                &available_language_servers
1971            ),
1972            language_server_names(&["deno", "eslint", "tailwind"])
1973        );
1974
1975        // Adding a language server not in the list of available language servers adds it to the list.
1976        assert_eq!(
1977            LanguageSettings::resolve_language_servers(
1978                &[
1979                    "my-cool-language-server".into(),
1980                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1981                ],
1982                &available_language_servers
1983            ),
1984            language_server_names(&[
1985                "my-cool-language-server",
1986                "typescript-language-server",
1987                "biome",
1988                "deno",
1989                "eslint",
1990                "tailwind",
1991            ])
1992        );
1993    }
1994}