language_settings.rs

   1//! Provides `language`-related settings.
   2
   3use crate::{File, Language, LanguageName, LanguageServerName};
   4use anyhow::Result;
   5use collections::{HashMap, HashSet};
   6use core::slice;
   7use ec4rs::{
   8    property::{FinalNewline, IndentSize, IndentStyle, TabWidth, TrimTrailingWs},
   9    Properties as EditorconfigProperties,
  10};
  11use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
  12use gpui::App;
  13use itertools::{Either, Itertools};
  14use schemars::{
  15    schema::{InstanceType, ObjectValidation, Schema, SchemaObject, SingleOrVec},
  16    JsonSchema,
  17};
  18use serde::{
  19    de::{self, IntoDeserializer, MapAccess, SeqAccess, Visitor},
  20    Deserialize, Deserializer, Serialize,
  21};
  22use serde_json::Value;
  23use settings::{
  24    add_references_to_properties, Settings, SettingsLocation, SettingsSources, SettingsStore,
  25};
  26use std::{borrow::Cow, num::NonZeroU32, path::Path, sync::Arc};
  27use util::serde::default_true;
  28
  29/// Initializes the language settings.
  30pub fn init(cx: &mut App) {
  31    AllLanguageSettings::register(cx);
  32}
  33
  34/// Returns the settings for the specified language from the provided file.
  35pub fn language_settings<'a>(
  36    language: Option<LanguageName>,
  37    file: Option<&'a Arc<dyn File>>,
  38    cx: &'a App,
  39) -> Cow<'a, LanguageSettings> {
  40    let location = file.map(|f| SettingsLocation {
  41        worktree_id: f.worktree_id(cx),
  42        path: f.path().as_ref(),
  43    });
  44    AllLanguageSettings::get(location, cx).language(location, language.as_ref(), cx)
  45}
  46
  47/// Returns the settings for all languages from the provided file.
  48pub fn all_language_settings<'a>(
  49    file: Option<&'a Arc<dyn File>>,
  50    cx: &'a App,
  51) -> &'a AllLanguageSettings {
  52    let location = file.map(|f| SettingsLocation {
  53        worktree_id: f.worktree_id(cx),
  54        path: f.path().as_ref(),
  55    });
  56    AllLanguageSettings::get(location, cx)
  57}
  58
  59/// The settings for all languages.
  60#[derive(Debug, Clone)]
  61pub struct AllLanguageSettings {
  62    /// The edit prediction settings.
  63    pub inline_completions: InlineCompletionSettings,
  64    defaults: LanguageSettings,
  65    languages: HashMap<LanguageName, LanguageSettings>,
  66    pub(crate) file_types: HashMap<Arc<str>, GlobSet>,
  67}
  68
  69/// The settings for a particular language.
  70#[derive(Debug, Clone, Deserialize)]
  71pub struct LanguageSettings {
  72    /// How many columns a tab should occupy.
  73    pub tab_size: NonZeroU32,
  74    /// Whether to indent lines using tab characters, as opposed to multiple
  75    /// spaces.
  76    pub hard_tabs: bool,
  77    /// How to soft-wrap long lines of text.
  78    pub soft_wrap: SoftWrap,
  79    /// The column at which to soft-wrap lines, for buffers where soft-wrap
  80    /// is enabled.
  81    pub preferred_line_length: u32,
  82    // Whether to show wrap guides (vertical rulers) in the editor.
  83    // Setting this to true will show a guide at the 'preferred_line_length' value
  84    // if softwrap is set to 'preferred_line_length', and will show any
  85    // additional guides as specified by the 'wrap_guides' setting.
  86    pub show_wrap_guides: bool,
  87    /// Character counts at which to show wrap guides (vertical rulers) in the editor.
  88    pub wrap_guides: Vec<usize>,
  89    /// Indent guide related settings.
  90    pub indent_guides: IndentGuideSettings,
  91    /// Whether or not to perform a buffer format before saving.
  92    pub format_on_save: FormatOnSave,
  93    /// Whether or not to remove any trailing whitespace from lines of a buffer
  94    /// before saving it.
  95    pub remove_trailing_whitespace_on_save: bool,
  96    /// Whether or not to ensure there's a single newline at the end of a buffer
  97    /// when saving it.
  98    pub ensure_final_newline_on_save: bool,
  99    /// How to perform a buffer format.
 100    pub formatter: SelectedFormatter,
 101    /// Zed's Prettier integration settings.
 102    pub prettier: PrettierSettings,
 103    /// Whether to use language servers to provide code intelligence.
 104    pub enable_language_server: bool,
 105    /// The list of language servers to use (or disable) for this language.
 106    ///
 107    /// This array should consist of language server IDs, as well as the following
 108    /// special tokens:
 109    /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
 110    /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
 111    pub language_servers: Vec<String>,
 112    /// Controls whether edit predictions are shown immediately (true)
 113    /// or manually by triggering `editor::ShowInlineCompletion` (false).
 114    pub show_inline_completions: bool,
 115    /// Controls whether edit predictions are shown in the given language
 116    /// scopes.
 117    pub inline_completions_disabled_in: Vec<String>,
 118    /// Whether to show tabs and spaces in the editor.
 119    pub show_whitespaces: ShowWhitespaceSetting,
 120    /// Whether to start a new line with a comment when a previous line is a comment as well.
 121    pub extend_comment_on_newline: bool,
 122    /// Inlay hint related settings.
 123    pub inlay_hints: InlayHintSettings,
 124    /// Whether to automatically close brackets.
 125    pub use_autoclose: bool,
 126    /// Whether to automatically surround text with brackets.
 127    pub use_auto_surround: bool,
 128    /// Whether to use additional LSP queries to format (and amend) the code after
 129    /// every "trigger" symbol input, defined by LSP server capabilities.
 130    pub use_on_type_format: bool,
 131    /// Whether indentation of pasted content should be adjusted based on the context.
 132    pub auto_indent_on_paste: bool,
 133    // Controls how the editor handles the autoclosed characters.
 134    pub always_treat_brackets_as_autoclosed: bool,
 135    /// Which code actions to run on save
 136    pub code_actions_on_format: HashMap<String, bool>,
 137    /// Whether to perform linked edits
 138    pub linked_edits: bool,
 139    /// Task configuration for this language.
 140    pub tasks: LanguageTaskConfig,
 141    /// Whether to pop the completions menu while typing in an editor without
 142    /// explicitly requesting it.
 143    pub show_completions_on_input: bool,
 144    /// Whether to display inline and alongside documentation for items in the
 145    /// completions menu.
 146    pub show_completion_documentation: bool,
 147}
 148
 149impl LanguageSettings {
 150    /// A token representing the rest of the available language servers.
 151    const REST_OF_LANGUAGE_SERVERS: &'static str = "...";
 152
 153    /// Returns the customized list of language servers from the list of
 154    /// available language servers.
 155    pub fn customized_language_servers(
 156        &self,
 157        available_language_servers: &[LanguageServerName],
 158    ) -> Vec<LanguageServerName> {
 159        Self::resolve_language_servers(&self.language_servers, available_language_servers)
 160    }
 161
 162    pub(crate) fn resolve_language_servers(
 163        configured_language_servers: &[String],
 164        available_language_servers: &[LanguageServerName],
 165    ) -> Vec<LanguageServerName> {
 166        let (disabled_language_servers, enabled_language_servers): (
 167            Vec<LanguageServerName>,
 168            Vec<LanguageServerName>,
 169        ) = configured_language_servers.iter().partition_map(
 170            |language_server| match language_server.strip_prefix('!') {
 171                Some(disabled) => Either::Left(LanguageServerName(disabled.to_string().into())),
 172                None => Either::Right(LanguageServerName(language_server.clone().into())),
 173            },
 174        );
 175
 176        let rest = available_language_servers
 177            .iter()
 178            .filter(|&available_language_server| {
 179                !disabled_language_servers.contains(&available_language_server)
 180                    && !enabled_language_servers.contains(&available_language_server)
 181            })
 182            .cloned()
 183            .collect::<Vec<_>>();
 184
 185        enabled_language_servers
 186            .into_iter()
 187            .flat_map(|language_server| {
 188                if language_server.0.as_ref() == Self::REST_OF_LANGUAGE_SERVERS {
 189                    rest.clone()
 190                } else {
 191                    vec![language_server.clone()]
 192                }
 193            })
 194            .collect::<Vec<_>>()
 195    }
 196}
 197
 198/// The provider that supplies edit predictions.
 199#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
 200#[serde(rename_all = "snake_case")]
 201pub enum InlineCompletionProvider {
 202    None,
 203    #[default]
 204    Copilot,
 205    Supermaven,
 206    Zed,
 207}
 208
 209/// The settings for edit predictions, such as [GitHub Copilot](https://github.com/features/copilot)
 210/// or [Supermaven](https://supermaven.com).
 211#[derive(Clone, Debug, Default)]
 212pub struct InlineCompletionSettings {
 213    /// The provider that supplies edit predictions.
 214    pub provider: InlineCompletionProvider,
 215    /// A list of globs representing files that edit predictions should be disabled for.
 216    pub disabled_globs: Vec<GlobMatcher>,
 217    /// When to show edit predictions previews in buffer.
 218    pub inline_preview: InlineCompletionPreviewMode,
 219}
 220
 221/// The mode in which edit predictions should be displayed.
 222#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
 223#[serde(rename_all = "snake_case")]
 224pub enum InlineCompletionPreviewMode {
 225    /// Display inline when there are no language server completions available.
 226    #[default]
 227    Auto,
 228    /// Display inline when holding modifier key (alt by default).
 229    WhenHoldingModifier,
 230}
 231
 232/// The settings for all languages.
 233#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
 234pub struct AllLanguageSettingsContent {
 235    /// The settings for enabling/disabling features.
 236    #[serde(default)]
 237    pub features: Option<FeaturesContent>,
 238    /// The edit prediction settings.
 239    #[serde(default)]
 240    pub inline_completions: Option<InlineCompletionSettingsContent>,
 241    /// The default language settings.
 242    #[serde(flatten)]
 243    pub defaults: LanguageSettingsContent,
 244    /// The settings for individual languages.
 245    #[serde(default)]
 246    pub languages: HashMap<LanguageName, LanguageSettingsContent>,
 247    /// Settings for associating file extensions and filenames
 248    /// with languages.
 249    #[serde(default)]
 250    pub file_types: HashMap<Arc<str>, Vec<String>>,
 251}
 252
 253/// The settings for a particular language.
 254#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
 255pub struct LanguageSettingsContent {
 256    /// How many columns a tab should occupy.
 257    ///
 258    /// Default: 4
 259    #[serde(default)]
 260    pub tab_size: Option<NonZeroU32>,
 261    /// Whether to indent lines using tab characters, as opposed to multiple
 262    /// spaces.
 263    ///
 264    /// Default: false
 265    #[serde(default)]
 266    pub hard_tabs: Option<bool>,
 267    /// How to soft-wrap long lines of text.
 268    ///
 269    /// Default: none
 270    #[serde(default)]
 271    pub soft_wrap: Option<SoftWrap>,
 272    /// The column at which to soft-wrap lines, for buffers where soft-wrap
 273    /// is enabled.
 274    ///
 275    /// Default: 80
 276    #[serde(default)]
 277    pub preferred_line_length: Option<u32>,
 278    /// Whether to show wrap guides in the editor. Setting this to true will
 279    /// show a guide at the 'preferred_line_length' value if softwrap is set to
 280    /// 'preferred_line_length', and will show any additional guides as specified
 281    /// by the 'wrap_guides' setting.
 282    ///
 283    /// Default: true
 284    #[serde(default)]
 285    pub show_wrap_guides: Option<bool>,
 286    /// Character counts at which to show wrap guides in the editor.
 287    ///
 288    /// Default: []
 289    #[serde(default)]
 290    pub wrap_guides: Option<Vec<usize>>,
 291    /// Indent guide related settings.
 292    #[serde(default)]
 293    pub indent_guides: Option<IndentGuideSettings>,
 294    /// Whether or not to perform a buffer format before saving.
 295    ///
 296    /// Default: on
 297    #[serde(default)]
 298    pub format_on_save: Option<FormatOnSave>,
 299    /// Whether or not to remove any trailing whitespace from lines of a buffer
 300    /// before saving it.
 301    ///
 302    /// Default: true
 303    #[serde(default)]
 304    pub remove_trailing_whitespace_on_save: Option<bool>,
 305    /// Whether or not to ensure there's a single newline at the end of a buffer
 306    /// when saving it.
 307    ///
 308    /// Default: true
 309    #[serde(default)]
 310    pub ensure_final_newline_on_save: Option<bool>,
 311    /// How to perform a buffer format.
 312    ///
 313    /// Default: auto
 314    #[serde(default)]
 315    pub formatter: Option<SelectedFormatter>,
 316    /// Zed's Prettier integration settings.
 317    /// Allows to enable/disable formatting with Prettier
 318    /// and configure default Prettier, used when no project-level Prettier installation is found.
 319    ///
 320    /// Default: off
 321    #[serde(default)]
 322    pub prettier: Option<PrettierSettings>,
 323    /// Whether to use language servers to provide code intelligence.
 324    ///
 325    /// Default: true
 326    #[serde(default)]
 327    pub enable_language_server: Option<bool>,
 328    /// The list of language servers to use (or disable) for this language.
 329    ///
 330    /// This array should consist of language server IDs, as well as the following
 331    /// special tokens:
 332    /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
 333    /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
 334    ///
 335    /// Default: ["..."]
 336    #[serde(default)]
 337    pub language_servers: Option<Vec<String>>,
 338    /// Controls whether edit predictions are shown immediately (true)
 339    /// or manually by triggering `editor::ShowInlineCompletion` (false).
 340    ///
 341    /// Default: true
 342    #[serde(default)]
 343    pub show_inline_completions: Option<bool>,
 344    /// Controls whether edit predictions are shown in the given language
 345    /// scopes.
 346    ///
 347    /// Example: ["string", "comment"]
 348    ///
 349    /// Default: []
 350    #[serde(default)]
 351    pub inline_completions_disabled_in: Option<Vec<String>>,
 352    /// Whether to show tabs and spaces in the editor.
 353    #[serde(default)]
 354    pub show_whitespaces: Option<ShowWhitespaceSetting>,
 355    /// Whether to start a new line with a comment when a previous line is a comment as well.
 356    ///
 357    /// Default: true
 358    #[serde(default)]
 359    pub extend_comment_on_newline: Option<bool>,
 360    /// Inlay hint related settings.
 361    #[serde(default)]
 362    pub inlay_hints: Option<InlayHintSettings>,
 363    /// Whether to automatically type closing characters for you. For example,
 364    /// when you type (, Zed will automatically add a closing ) at the correct position.
 365    ///
 366    /// Default: true
 367    pub use_autoclose: Option<bool>,
 368    /// Whether to automatically surround text with characters for you. For example,
 369    /// when you select text and type (, Zed will automatically surround text with ().
 370    ///
 371    /// Default: true
 372    pub use_auto_surround: Option<bool>,
 373    /// Controls how the editor handles the autoclosed characters.
 374    /// When set to `false`(default), skipping over and auto-removing of the closing characters
 375    /// happen only for auto-inserted characters.
 376    /// Otherwise(when `true`), the closing characters are always skipped over and auto-removed
 377    /// no matter how they were inserted.
 378    ///
 379    /// Default: false
 380    pub always_treat_brackets_as_autoclosed: Option<bool>,
 381    /// Whether to use additional LSP queries to format (and amend) the code after
 382    /// every "trigger" symbol input, defined by LSP server capabilities.
 383    ///
 384    /// Default: true
 385    pub use_on_type_format: Option<bool>,
 386    /// Which code actions to run on save after the formatter.
 387    /// These are not run if formatting is off.
 388    ///
 389    /// Default: {} (or {"source.organizeImports": true} for Go).
 390    pub code_actions_on_format: Option<HashMap<String, bool>>,
 391    /// Whether to perform linked edits of associated ranges, if the language server supports it.
 392    /// For example, when editing opening <html> tag, the contents of the closing </html> tag will be edited as well.
 393    ///
 394    /// Default: true
 395    pub linked_edits: Option<bool>,
 396    /// Whether indentation of pasted content should be adjusted based on the context.
 397    ///
 398    /// Default: true
 399    pub auto_indent_on_paste: Option<bool>,
 400    /// Task configuration for this language.
 401    ///
 402    /// Default: {}
 403    pub tasks: Option<LanguageTaskConfig>,
 404    /// Whether to pop the completions menu while typing in an editor without
 405    /// explicitly requesting it.
 406    ///
 407    /// Default: true
 408    pub show_completions_on_input: Option<bool>,
 409    /// Whether to display inline and alongside documentation for items in the
 410    /// completions menu.
 411    ///
 412    /// Default: true
 413    pub show_completion_documentation: Option<bool>,
 414}
 415
 416/// The contents of the edit prediction settings.
 417#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)]
 418pub struct InlineCompletionSettingsContent {
 419    /// A list of globs representing files that edit predictions should be disabled for.
 420    #[serde(default)]
 421    pub disabled_globs: Option<Vec<String>>,
 422    /// When to show edit predictions previews in buffer.
 423    #[serde(default)]
 424    pub inline_preview: InlineCompletionPreviewMode,
 425}
 426
 427/// The settings for enabling/disabling features.
 428#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
 429#[serde(rename_all = "snake_case")]
 430pub struct FeaturesContent {
 431    /// Whether the GitHub Copilot feature is enabled.
 432    pub copilot: Option<bool>,
 433    /// Determines which edit prediction provider to use.
 434    pub inline_completion_provider: Option<InlineCompletionProvider>,
 435}
 436
 437/// Controls the soft-wrapping behavior in the editor.
 438#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
 439#[serde(rename_all = "snake_case")]
 440pub enum SoftWrap {
 441    /// Prefer a single line generally, unless an overly long line is encountered.
 442    None,
 443    /// Deprecated: use None instead. Left to avoid breaking existing users' configs.
 444    /// Prefer a single line generally, unless an overly long line is encountered.
 445    PreferLine,
 446    /// Soft wrap lines that exceed the editor width.
 447    EditorWidth,
 448    /// Soft wrap lines at the preferred line length.
 449    PreferredLineLength,
 450    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
 451    Bounded,
 452}
 453
 454/// Controls the behavior of formatting files when they are saved.
 455#[derive(Debug, Clone, PartialEq, Eq)]
 456pub enum FormatOnSave {
 457    /// Files should be formatted on save.
 458    On,
 459    /// Files should not be formatted on save.
 460    Off,
 461    List(FormatterList),
 462}
 463
 464impl JsonSchema for FormatOnSave {
 465    fn schema_name() -> String {
 466        "OnSaveFormatter".into()
 467    }
 468
 469    fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> Schema {
 470        let mut schema = SchemaObject::default();
 471        let formatter_schema = Formatter::json_schema(generator);
 472        schema.instance_type = Some(
 473            vec![
 474                InstanceType::Object,
 475                InstanceType::String,
 476                InstanceType::Array,
 477            ]
 478            .into(),
 479        );
 480
 481        let valid_raw_values = SchemaObject {
 482            enum_values: Some(vec![
 483                Value::String("on".into()),
 484                Value::String("off".into()),
 485                Value::String("prettier".into()),
 486                Value::String("language_server".into()),
 487            ]),
 488            ..Default::default()
 489        };
 490        let mut nested_values = SchemaObject::default();
 491
 492        nested_values.array().items = Some(formatter_schema.clone().into());
 493
 494        schema.subschemas().any_of = Some(vec![
 495            nested_values.into(),
 496            valid_raw_values.into(),
 497            formatter_schema,
 498        ]);
 499        schema.into()
 500    }
 501}
 502
 503impl Serialize for FormatOnSave {
 504    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
 505    where
 506        S: serde::Serializer,
 507    {
 508        match self {
 509            Self::On => serializer.serialize_str("on"),
 510            Self::Off => serializer.serialize_str("off"),
 511            Self::List(list) => list.serialize(serializer),
 512        }
 513    }
 514}
 515
 516impl<'de> Deserialize<'de> for FormatOnSave {
 517    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 518    where
 519        D: Deserializer<'de>,
 520    {
 521        struct FormatDeserializer;
 522
 523        impl<'d> Visitor<'d> for FormatDeserializer {
 524            type Value = FormatOnSave;
 525
 526            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
 527                formatter.write_str("a valid on-save formatter kind")
 528            }
 529            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
 530            where
 531                E: serde::de::Error,
 532            {
 533                if v == "on" {
 534                    Ok(Self::Value::On)
 535                } else if v == "off" {
 536                    Ok(Self::Value::Off)
 537                } else if v == "language_server" {
 538                    Ok(Self::Value::List(FormatterList(
 539                        Formatter::LanguageServer { name: None }.into(),
 540                    )))
 541                } else {
 542                    let ret: Result<FormatterList, _> =
 543                        Deserialize::deserialize(v.into_deserializer());
 544                    ret.map(Self::Value::List)
 545                }
 546            }
 547            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
 548            where
 549                A: MapAccess<'d>,
 550            {
 551                let ret: Result<FormatterList, _> =
 552                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
 553                ret.map(Self::Value::List)
 554            }
 555            fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
 556            where
 557                A: SeqAccess<'d>,
 558            {
 559                let ret: Result<FormatterList, _> =
 560                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
 561                ret.map(Self::Value::List)
 562            }
 563        }
 564        deserializer.deserialize_any(FormatDeserializer)
 565    }
 566}
 567
 568/// Controls how whitespace should be displayedin the editor.
 569#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
 570#[serde(rename_all = "snake_case")]
 571pub enum ShowWhitespaceSetting {
 572    /// Draw whitespace only for the selected text.
 573    Selection,
 574    /// Do not draw any tabs or spaces.
 575    None,
 576    /// Draw all invisible symbols.
 577    All,
 578    /// Draw whitespaces at boundaries only.
 579    ///
 580    /// For a whitespace to be on a boundary, any of the following conditions need to be met:
 581    /// - It is a tab
 582    /// - It is adjacent to an edge (start or end)
 583    /// - It is adjacent to a whitespace (left or right)
 584    Boundary,
 585}
 586
 587/// Controls which formatter should be used when formatting code.
 588#[derive(Clone, Debug, Default, PartialEq, Eq)]
 589pub enum SelectedFormatter {
 590    /// Format files using Zed's Prettier integration (if applicable),
 591    /// or falling back to formatting via language server.
 592    #[default]
 593    Auto,
 594    List(FormatterList),
 595}
 596
 597impl JsonSchema for SelectedFormatter {
 598    fn schema_name() -> String {
 599        "Formatter".into()
 600    }
 601
 602    fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> Schema {
 603        let mut schema = SchemaObject::default();
 604        let formatter_schema = Formatter::json_schema(generator);
 605        schema.instance_type = Some(
 606            vec![
 607                InstanceType::Object,
 608                InstanceType::String,
 609                InstanceType::Array,
 610            ]
 611            .into(),
 612        );
 613
 614        let valid_raw_values = SchemaObject {
 615            enum_values: Some(vec![
 616                Value::String("auto".into()),
 617                Value::String("prettier".into()),
 618                Value::String("language_server".into()),
 619            ]),
 620            ..Default::default()
 621        };
 622
 623        let mut nested_values = SchemaObject::default();
 624
 625        nested_values.array().items = Some(formatter_schema.clone().into());
 626
 627        schema.subschemas().any_of = Some(vec![
 628            nested_values.into(),
 629            valid_raw_values.into(),
 630            formatter_schema,
 631        ]);
 632        schema.into()
 633    }
 634}
 635
 636impl Serialize for SelectedFormatter {
 637    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
 638    where
 639        S: serde::Serializer,
 640    {
 641        match self {
 642            SelectedFormatter::Auto => serializer.serialize_str("auto"),
 643            SelectedFormatter::List(list) => list.serialize(serializer),
 644        }
 645    }
 646}
 647impl<'de> Deserialize<'de> for SelectedFormatter {
 648    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 649    where
 650        D: Deserializer<'de>,
 651    {
 652        struct FormatDeserializer;
 653
 654        impl<'d> Visitor<'d> for FormatDeserializer {
 655            type Value = SelectedFormatter;
 656
 657            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
 658                formatter.write_str("a valid formatter kind")
 659            }
 660            fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
 661            where
 662                E: serde::de::Error,
 663            {
 664                if v == "auto" {
 665                    Ok(Self::Value::Auto)
 666                } else if v == "language_server" {
 667                    Ok(Self::Value::List(FormatterList(
 668                        Formatter::LanguageServer { name: None }.into(),
 669                    )))
 670                } else {
 671                    let ret: Result<FormatterList, _> =
 672                        Deserialize::deserialize(v.into_deserializer());
 673                    ret.map(SelectedFormatter::List)
 674                }
 675            }
 676            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
 677            where
 678                A: MapAccess<'d>,
 679            {
 680                let ret: Result<FormatterList, _> =
 681                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map));
 682                ret.map(SelectedFormatter::List)
 683            }
 684            fn visit_seq<A>(self, map: A) -> Result<Self::Value, A::Error>
 685            where
 686                A: SeqAccess<'d>,
 687            {
 688                let ret: Result<FormatterList, _> =
 689                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(map));
 690                ret.map(SelectedFormatter::List)
 691            }
 692        }
 693        deserializer.deserialize_any(FormatDeserializer)
 694    }
 695}
 696/// Controls which formatter should be used when formatting code.
 697#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
 698#[serde(rename_all = "snake_case", transparent)]
 699pub struct FormatterList(pub SingleOrVec<Formatter>);
 700
 701impl AsRef<[Formatter]> for FormatterList {
 702    fn as_ref(&self) -> &[Formatter] {
 703        match &self.0 {
 704            SingleOrVec::Single(single) => slice::from_ref(single),
 705            SingleOrVec::Vec(v) => v,
 706        }
 707    }
 708}
 709
 710/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
 711#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
 712#[serde(rename_all = "snake_case")]
 713pub enum Formatter {
 714    /// Format code using the current language server.
 715    LanguageServer { name: Option<String> },
 716    /// Format code using Zed's Prettier integration.
 717    Prettier,
 718    /// Format code using an external command.
 719    External {
 720        /// The external program to run.
 721        command: Arc<str>,
 722        /// The arguments to pass to the program.
 723        arguments: Option<Arc<[String]>>,
 724    },
 725    /// Files should be formatted using code actions executed by language servers.
 726    CodeActions(HashMap<String, bool>),
 727}
 728
 729/// The settings for indent guides.
 730#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 731pub struct IndentGuideSettings {
 732    /// Whether to display indent guides in the editor.
 733    ///
 734    /// Default: true
 735    #[serde(default = "default_true")]
 736    pub enabled: bool,
 737    /// The width of the indent guides in pixels, between 1 and 10.
 738    ///
 739    /// Default: 1
 740    #[serde(default = "line_width")]
 741    pub line_width: u32,
 742    /// The width of the active indent guide in pixels, between 1 and 10.
 743    ///
 744    /// Default: 1
 745    #[serde(default = "active_line_width")]
 746    pub active_line_width: u32,
 747    /// Determines how indent guides are colored.
 748    ///
 749    /// Default: Fixed
 750    #[serde(default)]
 751    pub coloring: IndentGuideColoring,
 752    /// Determines how indent guide backgrounds are colored.
 753    ///
 754    /// Default: Disabled
 755    #[serde(default)]
 756    pub background_coloring: IndentGuideBackgroundColoring,
 757}
 758
 759fn line_width() -> u32 {
 760    1
 761}
 762
 763fn active_line_width() -> u32 {
 764    line_width()
 765}
 766
 767/// Determines how indent guides are colored.
 768#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 769#[serde(rename_all = "snake_case")]
 770pub enum IndentGuideColoring {
 771    /// Do not render any lines for indent guides.
 772    Disabled,
 773    /// Use the same color for all indentation levels.
 774    #[default]
 775    Fixed,
 776    /// Use a different color for each indentation level.
 777    IndentAware,
 778}
 779
 780/// Determines how indent guide backgrounds are colored.
 781#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 782#[serde(rename_all = "snake_case")]
 783pub enum IndentGuideBackgroundColoring {
 784    /// Do not render any background for indent guides.
 785    #[default]
 786    Disabled,
 787    /// Use a different color for each indentation level.
 788    IndentAware,
 789}
 790
 791/// The settings for inlay hints.
 792#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
 793pub struct InlayHintSettings {
 794    /// Global switch to toggle hints on and off.
 795    ///
 796    /// Default: false
 797    #[serde(default)]
 798    pub enabled: bool,
 799    /// Whether type hints should be shown.
 800    ///
 801    /// Default: true
 802    #[serde(default = "default_true")]
 803    pub show_type_hints: bool,
 804    /// Whether parameter hints should be shown.
 805    ///
 806    /// Default: true
 807    #[serde(default = "default_true")]
 808    pub show_parameter_hints: bool,
 809    /// Whether other hints should be shown.
 810    ///
 811    /// Default: true
 812    #[serde(default = "default_true")]
 813    pub show_other_hints: bool,
 814    /// Whether to show a background for inlay hints.
 815    ///
 816    /// If set to `true`, the background will use the `hint.background` color
 817    /// from the current theme.
 818    ///
 819    /// Default: false
 820    #[serde(default)]
 821    pub show_background: bool,
 822    /// Whether or not to debounce inlay hints updates after buffer edits.
 823    ///
 824    /// Set to 0 to disable debouncing.
 825    ///
 826    /// Default: 700
 827    #[serde(default = "edit_debounce_ms")]
 828    pub edit_debounce_ms: u64,
 829    /// Whether or not to debounce inlay hints updates after buffer scrolls.
 830    ///
 831    /// Set to 0 to disable debouncing.
 832    ///
 833    /// Default: 50
 834    #[serde(default = "scroll_debounce_ms")]
 835    pub scroll_debounce_ms: u64,
 836}
 837
 838fn edit_debounce_ms() -> u64 {
 839    700
 840}
 841
 842fn scroll_debounce_ms() -> u64 {
 843    50
 844}
 845
 846/// The task settings for a particular language.
 847#[derive(Debug, Clone, Deserialize, PartialEq, Serialize, JsonSchema)]
 848pub struct LanguageTaskConfig {
 849    /// Extra task variables to set for a particular language.
 850    pub variables: HashMap<String, String>,
 851}
 852
 853impl InlayHintSettings {
 854    /// Returns the kinds of inlay hints that are enabled based on the settings.
 855    pub fn enabled_inlay_hint_kinds(&self) -> HashSet<Option<InlayHintKind>> {
 856        let mut kinds = HashSet::default();
 857        if self.show_type_hints {
 858            kinds.insert(Some(InlayHintKind::Type));
 859        }
 860        if self.show_parameter_hints {
 861            kinds.insert(Some(InlayHintKind::Parameter));
 862        }
 863        if self.show_other_hints {
 864            kinds.insert(None);
 865        }
 866        kinds
 867    }
 868}
 869
 870impl AllLanguageSettings {
 871    /// Returns the [`LanguageSettings`] for the language with the specified name.
 872    pub fn language<'a>(
 873        &'a self,
 874        location: Option<SettingsLocation<'a>>,
 875        language_name: Option<&LanguageName>,
 876        cx: &'a App,
 877    ) -> Cow<'a, LanguageSettings> {
 878        let settings = language_name
 879            .and_then(|name| self.languages.get(name))
 880            .unwrap_or(&self.defaults);
 881
 882        let editorconfig_properties = location.and_then(|location| {
 883            cx.global::<SettingsStore>()
 884                .editorconfig_properties(location.worktree_id, location.path)
 885        });
 886        if let Some(editorconfig_properties) = editorconfig_properties {
 887            let mut settings = settings.clone();
 888            merge_with_editorconfig(&mut settings, &editorconfig_properties);
 889            Cow::Owned(settings)
 890        } else {
 891            Cow::Borrowed(settings)
 892        }
 893    }
 894
 895    /// Returns whether edit predictions are enabled for the given path.
 896    pub fn inline_completions_enabled_for_path(&self, path: &Path) -> bool {
 897        !self
 898            .inline_completions
 899            .disabled_globs
 900            .iter()
 901            .any(|glob| glob.is_match(path))
 902    }
 903
 904    /// Returns whether edit predictions are enabled for the given language and path.
 905    pub fn show_inline_completions(&self, language: Option<&Arc<Language>>, cx: &App) -> bool {
 906        self.language(None, language.map(|l| l.name()).as_ref(), cx)
 907            .show_inline_completions
 908    }
 909
 910    /// Returns the edit predictions preview mode for the given language and path.
 911    pub fn inline_completions_preview_mode(&self) -> InlineCompletionPreviewMode {
 912        self.inline_completions.inline_preview
 913    }
 914}
 915
 916fn merge_with_editorconfig(settings: &mut LanguageSettings, cfg: &EditorconfigProperties) {
 917    let tab_size = cfg.get::<IndentSize>().ok().and_then(|v| match v {
 918        IndentSize::Value(u) => NonZeroU32::new(u as u32),
 919        IndentSize::UseTabWidth => cfg.get::<TabWidth>().ok().and_then(|w| match w {
 920            TabWidth::Value(u) => NonZeroU32::new(u as u32),
 921        }),
 922    });
 923    let hard_tabs = cfg
 924        .get::<IndentStyle>()
 925        .map(|v| v.eq(&IndentStyle::Tabs))
 926        .ok();
 927    let ensure_final_newline_on_save = cfg
 928        .get::<FinalNewline>()
 929        .map(|v| match v {
 930            FinalNewline::Value(b) => b,
 931        })
 932        .ok();
 933    let remove_trailing_whitespace_on_save = cfg
 934        .get::<TrimTrailingWs>()
 935        .map(|v| match v {
 936            TrimTrailingWs::Value(b) => b,
 937        })
 938        .ok();
 939    fn merge<T>(target: &mut T, value: Option<T>) {
 940        if let Some(value) = value {
 941            *target = value;
 942        }
 943    }
 944    merge(&mut settings.tab_size, tab_size);
 945    merge(&mut settings.hard_tabs, hard_tabs);
 946    merge(
 947        &mut settings.remove_trailing_whitespace_on_save,
 948        remove_trailing_whitespace_on_save,
 949    );
 950    merge(
 951        &mut settings.ensure_final_newline_on_save,
 952        ensure_final_newline_on_save,
 953    );
 954}
 955
 956/// The kind of an inlay hint.
 957#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 958pub enum InlayHintKind {
 959    /// An inlay hint for a type.
 960    Type,
 961    /// An inlay hint for a parameter.
 962    Parameter,
 963}
 964
 965impl InlayHintKind {
 966    /// Returns the [`InlayHintKind`] from the given name.
 967    ///
 968    /// Returns `None` if `name` does not match any of the expected
 969    /// string representations.
 970    pub fn from_name(name: &str) -> Option<Self> {
 971        match name {
 972            "type" => Some(InlayHintKind::Type),
 973            "parameter" => Some(InlayHintKind::Parameter),
 974            _ => None,
 975        }
 976    }
 977
 978    /// Returns the name of this [`InlayHintKind`].
 979    pub fn name(&self) -> &'static str {
 980        match self {
 981            InlayHintKind::Type => "type",
 982            InlayHintKind::Parameter => "parameter",
 983        }
 984    }
 985}
 986
 987impl settings::Settings for AllLanguageSettings {
 988    const KEY: Option<&'static str> = None;
 989
 990    type FileContent = AllLanguageSettingsContent;
 991
 992    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
 993        let default_value = sources.default;
 994
 995        // A default is provided for all settings.
 996        let mut defaults: LanguageSettings =
 997            serde_json::from_value(serde_json::to_value(&default_value.defaults)?)?;
 998
 999        let mut languages = HashMap::default();
1000        for (language_name, settings) in &default_value.languages {
1001            let mut language_settings = defaults.clone();
1002            merge_settings(&mut language_settings, settings);
1003            languages.insert(language_name.clone(), language_settings);
1004        }
1005
1006        let mut copilot_enabled = default_value.features.as_ref().and_then(|f| f.copilot);
1007        let mut inline_completion_provider = default_value
1008            .features
1009            .as_ref()
1010            .and_then(|f| f.inline_completion_provider);
1011        let mut inline_completions_preview = default_value
1012            .inline_completions
1013            .as_ref()
1014            .map(|inline_completions| inline_completions.inline_preview)
1015            .ok_or_else(Self::missing_default)?;
1016
1017        let mut completion_globs: HashSet<&String> = default_value
1018            .inline_completions
1019            .as_ref()
1020            .and_then(|c| c.disabled_globs.as_ref())
1021            .map(|globs| globs.iter().collect())
1022            .ok_or_else(Self::missing_default)?;
1023
1024        let mut file_types: HashMap<Arc<str>, GlobSet> = HashMap::default();
1025
1026        for (language, suffixes) in &default_value.file_types {
1027            let mut builder = GlobSetBuilder::new();
1028
1029            for suffix in suffixes {
1030                builder.add(Glob::new(suffix)?);
1031            }
1032
1033            file_types.insert(language.clone(), builder.build()?);
1034        }
1035
1036        for user_settings in sources.customizations() {
1037            if let Some(copilot) = user_settings.features.as_ref().and_then(|f| f.copilot) {
1038                copilot_enabled = Some(copilot);
1039            }
1040            if let Some(provider) = user_settings
1041                .features
1042                .as_ref()
1043                .and_then(|f| f.inline_completion_provider)
1044            {
1045                inline_completion_provider = Some(provider);
1046            }
1047
1048            if let Some(inline_completions) = user_settings.inline_completions.as_ref() {
1049                inline_completions_preview = inline_completions.inline_preview;
1050
1051                if let Some(disabled_globs) = inline_completions.disabled_globs.as_ref() {
1052                    completion_globs.extend(disabled_globs.iter());
1053                }
1054            }
1055
1056            // A user's global settings override the default global settings and
1057            // all default language-specific settings.
1058            merge_settings(&mut defaults, &user_settings.defaults);
1059            for language_settings in languages.values_mut() {
1060                merge_settings(language_settings, &user_settings.defaults);
1061            }
1062
1063            // A user's language-specific settings override default language-specific settings.
1064            for (language_name, user_language_settings) in &user_settings.languages {
1065                merge_settings(
1066                    languages
1067                        .entry(language_name.clone())
1068                        .or_insert_with(|| defaults.clone()),
1069                    user_language_settings,
1070                );
1071            }
1072
1073            for (language, suffixes) in &user_settings.file_types {
1074                let mut builder = GlobSetBuilder::new();
1075
1076                let default_value = default_value.file_types.get(&language.clone());
1077
1078                // Merge the default value with the user's value.
1079                if let Some(suffixes) = default_value {
1080                    for suffix in suffixes {
1081                        builder.add(Glob::new(suffix)?);
1082                    }
1083                }
1084
1085                for suffix in suffixes {
1086                    builder.add(Glob::new(suffix)?);
1087                }
1088
1089                file_types.insert(language.clone(), builder.build()?);
1090            }
1091        }
1092
1093        Ok(Self {
1094            inline_completions: InlineCompletionSettings {
1095                provider: if let Some(provider) = inline_completion_provider {
1096                    provider
1097                } else if copilot_enabled.unwrap_or(true) {
1098                    InlineCompletionProvider::Copilot
1099                } else {
1100                    InlineCompletionProvider::None
1101                },
1102                disabled_globs: completion_globs
1103                    .iter()
1104                    .filter_map(|g| Some(globset::Glob::new(g).ok()?.compile_matcher()))
1105                    .collect(),
1106                inline_preview: inline_completions_preview,
1107            },
1108            defaults,
1109            languages,
1110            file_types,
1111        })
1112    }
1113
1114    fn json_schema(
1115        generator: &mut schemars::gen::SchemaGenerator,
1116        params: &settings::SettingsJsonSchemaParams,
1117        _: &App,
1118    ) -> schemars::schema::RootSchema {
1119        let mut root_schema = generator.root_schema_for::<Self::FileContent>();
1120
1121        // Create a schema for a 'languages overrides' object, associating editor
1122        // settings with specific languages.
1123        assert!(root_schema
1124            .definitions
1125            .contains_key("LanguageSettingsContent"));
1126
1127        let languages_object_schema = SchemaObject {
1128            instance_type: Some(InstanceType::Object.into()),
1129            object: Some(Box::new(ObjectValidation {
1130                properties: params
1131                    .language_names
1132                    .iter()
1133                    .map(|name| {
1134                        (
1135                            name.clone(),
1136                            Schema::new_ref("#/definitions/LanguageSettingsContent".into()),
1137                        )
1138                    })
1139                    .collect(),
1140                ..Default::default()
1141            })),
1142            ..Default::default()
1143        };
1144
1145        root_schema
1146            .definitions
1147            .extend([("Languages".into(), languages_object_schema.into())]);
1148
1149        add_references_to_properties(
1150            &mut root_schema,
1151            &[("languages", "#/definitions/Languages")],
1152        );
1153
1154        root_schema
1155    }
1156}
1157
1158fn merge_settings(settings: &mut LanguageSettings, src: &LanguageSettingsContent) {
1159    fn merge<T>(target: &mut T, value: Option<T>) {
1160        if let Some(value) = value {
1161            *target = value;
1162        }
1163    }
1164
1165    merge(&mut settings.tab_size, src.tab_size);
1166    settings.tab_size = settings
1167        .tab_size
1168        .clamp(NonZeroU32::new(1).unwrap(), NonZeroU32::new(16).unwrap());
1169
1170    merge(&mut settings.hard_tabs, src.hard_tabs);
1171    merge(&mut settings.soft_wrap, src.soft_wrap);
1172    merge(&mut settings.use_autoclose, src.use_autoclose);
1173    merge(&mut settings.use_auto_surround, src.use_auto_surround);
1174    merge(&mut settings.use_on_type_format, src.use_on_type_format);
1175    merge(&mut settings.auto_indent_on_paste, src.auto_indent_on_paste);
1176    merge(
1177        &mut settings.always_treat_brackets_as_autoclosed,
1178        src.always_treat_brackets_as_autoclosed,
1179    );
1180    merge(&mut settings.show_wrap_guides, src.show_wrap_guides);
1181    merge(&mut settings.wrap_guides, src.wrap_guides.clone());
1182    merge(&mut settings.indent_guides, src.indent_guides);
1183    merge(
1184        &mut settings.code_actions_on_format,
1185        src.code_actions_on_format.clone(),
1186    );
1187    merge(&mut settings.linked_edits, src.linked_edits);
1188    merge(&mut settings.tasks, src.tasks.clone());
1189
1190    merge(
1191        &mut settings.preferred_line_length,
1192        src.preferred_line_length,
1193    );
1194    merge(&mut settings.formatter, src.formatter.clone());
1195    merge(&mut settings.prettier, src.prettier.clone());
1196    merge(&mut settings.format_on_save, src.format_on_save.clone());
1197    merge(
1198        &mut settings.remove_trailing_whitespace_on_save,
1199        src.remove_trailing_whitespace_on_save,
1200    );
1201    merge(
1202        &mut settings.ensure_final_newline_on_save,
1203        src.ensure_final_newline_on_save,
1204    );
1205    merge(
1206        &mut settings.enable_language_server,
1207        src.enable_language_server,
1208    );
1209    merge(&mut settings.language_servers, src.language_servers.clone());
1210    merge(
1211        &mut settings.show_inline_completions,
1212        src.show_inline_completions,
1213    );
1214    merge(
1215        &mut settings.inline_completions_disabled_in,
1216        src.inline_completions_disabled_in.clone(),
1217    );
1218    merge(&mut settings.show_whitespaces, src.show_whitespaces);
1219    merge(
1220        &mut settings.extend_comment_on_newline,
1221        src.extend_comment_on_newline,
1222    );
1223    merge(&mut settings.inlay_hints, src.inlay_hints);
1224    merge(
1225        &mut settings.show_completions_on_input,
1226        src.show_completions_on_input,
1227    );
1228    merge(
1229        &mut settings.show_completion_documentation,
1230        src.show_completion_documentation,
1231    );
1232}
1233
1234/// Allows to enable/disable formatting with Prettier
1235/// and configure default Prettier, used when no project-level Prettier installation is found.
1236/// Prettier formatting is disabled by default.
1237#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1238pub struct PrettierSettings {
1239    /// Enables or disables formatting with Prettier for a given language.
1240    #[serde(default)]
1241    pub allowed: bool,
1242
1243    /// Forces Prettier integration to use a specific parser name when formatting files with the language.
1244    #[serde(default)]
1245    pub parser: Option<String>,
1246
1247    /// Forces Prettier integration to use specific plugins when formatting files with the language.
1248    /// The default Prettier will be installed with these plugins.
1249    #[serde(default)]
1250    pub plugins: HashSet<String>,
1251
1252    /// Default Prettier options, in the format as in package.json section for Prettier.
1253    /// If project installs Prettier via its package.json, these options will be ignored.
1254    #[serde(flatten)]
1255    pub options: HashMap<String, serde_json::Value>,
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260    use super::*;
1261
1262    #[test]
1263    fn test_formatter_deserialization() {
1264        let raw_auto = "{\"formatter\": \"auto\"}";
1265        let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
1266        assert_eq!(settings.formatter, Some(SelectedFormatter::Auto));
1267        let raw = "{\"formatter\": \"language_server\"}";
1268        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1269        assert_eq!(
1270            settings.formatter,
1271            Some(SelectedFormatter::List(FormatterList(
1272                Formatter::LanguageServer { name: None }.into()
1273            )))
1274        );
1275        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
1276        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1277        assert_eq!(
1278            settings.formatter,
1279            Some(SelectedFormatter::List(FormatterList(
1280                vec![Formatter::LanguageServer { name: None }].into()
1281            )))
1282        );
1283        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"prettier\"]}";
1284        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
1285        assert_eq!(
1286            settings.formatter,
1287            Some(SelectedFormatter::List(FormatterList(
1288                vec![
1289                    Formatter::LanguageServer { name: None },
1290                    Formatter::Prettier
1291                ]
1292                .into()
1293            )))
1294        );
1295    }
1296
1297    #[test]
1298    fn test_formatter_deserialization_invalid() {
1299        let raw_auto = "{\"formatter\": {}}";
1300        let result: Result<LanguageSettingsContent, _> = serde_json::from_str(raw_auto);
1301        assert!(result.is_err());
1302    }
1303
1304    #[test]
1305    pub fn test_resolve_language_servers() {
1306        fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
1307            names
1308                .iter()
1309                .copied()
1310                .map(|name| LanguageServerName(name.to_string().into()))
1311                .collect::<Vec<_>>()
1312        }
1313
1314        let available_language_servers = language_server_names(&[
1315            "typescript-language-server",
1316            "biome",
1317            "deno",
1318            "eslint",
1319            "tailwind",
1320        ]);
1321
1322        // A value of just `["..."]` is the same as taking all of the available language servers.
1323        assert_eq!(
1324            LanguageSettings::resolve_language_servers(
1325                &[LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()],
1326                &available_language_servers,
1327            ),
1328            available_language_servers
1329        );
1330
1331        // Referencing one of the available language servers will change its order.
1332        assert_eq!(
1333            LanguageSettings::resolve_language_servers(
1334                &[
1335                    "biome".into(),
1336                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into(),
1337                    "deno".into()
1338                ],
1339                &available_language_servers
1340            ),
1341            language_server_names(&[
1342                "biome",
1343                "typescript-language-server",
1344                "eslint",
1345                "tailwind",
1346                "deno",
1347            ])
1348        );
1349
1350        // Negating an available language server removes it from the list.
1351        assert_eq!(
1352            LanguageSettings::resolve_language_servers(
1353                &[
1354                    "deno".into(),
1355                    "!typescript-language-server".into(),
1356                    "!biome".into(),
1357                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1358                ],
1359                &available_language_servers
1360            ),
1361            language_server_names(&["deno", "eslint", "tailwind"])
1362        );
1363
1364        // Adding a language server not in the list of available language servers adds it to the list.
1365        assert_eq!(
1366            LanguageSettings::resolve_language_servers(
1367                &[
1368                    "my-cool-language-server".into(),
1369                    LanguageSettings::REST_OF_LANGUAGE_SERVERS.into()
1370                ],
1371                &available_language_servers
1372            ),
1373            language_server_names(&[
1374                "my-cool-language-server",
1375                "typescript-language-server",
1376                "biome",
1377                "deno",
1378                "eslint",
1379                "tailwind",
1380            ])
1381        );
1382    }
1383}