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