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