language_settings.rs

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