language.rs

   1use std::num::NonZeroU32;
   2
   3use collections::{HashMap, HashSet};
   4use gpui::{Modifiers, SharedString};
   5use schemars::JsonSchema;
   6use serde::{Deserialize, Serialize, de::Error as _};
   7use settings_macros::{MergeFrom, with_fallible_options};
   8use std::sync::Arc;
   9
  10use crate::{ExtendingVec, merge_from};
  11
  12#[with_fallible_options]
  13#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
  14pub struct AllLanguageSettingsContent {
  15    /// The settings for enabling/disabling features.
  16    pub features: Option<FeaturesContent>,
  17    /// The edit prediction settings.
  18    pub edit_predictions: Option<EditPredictionSettingsContent>,
  19    /// The default language settings.
  20    #[serde(flatten)]
  21    pub defaults: LanguageSettingsContent,
  22    /// The settings for individual languages.
  23    #[serde(default)]
  24    pub languages: LanguageToSettingsMap,
  25    /// Settings for associating file extensions and filenames
  26    /// with languages.
  27    pub file_types: Option<HashMap<Arc<str>, ExtendingVec<String>>>,
  28}
  29
  30impl merge_from::MergeFrom for AllLanguageSettingsContent {
  31    fn merge_from(&mut self, other: &Self) {
  32        self.file_types.merge_from(&other.file_types);
  33        self.features.merge_from(&other.features);
  34        self.edit_predictions.merge_from(&other.edit_predictions);
  35
  36        // A user's global settings override the default global settings and
  37        // all default language-specific settings.
  38        //
  39        self.defaults.merge_from(&other.defaults);
  40        for language_settings in self.languages.0.values_mut() {
  41            language_settings.merge_from(&other.defaults);
  42        }
  43
  44        // A user's language-specific settings override default language-specific settings.
  45        for (language_name, user_language_settings) in &other.languages.0 {
  46            if let Some(existing) = self.languages.0.get_mut(language_name) {
  47                existing.merge_from(&user_language_settings);
  48            } else {
  49                let mut new_settings = self.defaults.clone();
  50                new_settings.merge_from(&user_language_settings);
  51
  52                self.languages.0.insert(language_name.clone(), new_settings);
  53            }
  54        }
  55    }
  56}
  57
  58/// The settings for enabling/disabling features.
  59#[with_fallible_options]
  60#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
  61#[serde(rename_all = "snake_case")]
  62pub struct FeaturesContent {
  63    /// Determines which edit prediction provider to use.
  64    pub edit_prediction_provider: Option<EditPredictionProvider>,
  65    /// Enables the experimental edit prediction context retrieval system.
  66    pub experimental_edit_prediction_context_retrieval: Option<bool>,
  67}
  68
  69/// The provider that supplies edit predictions.
  70#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, JsonSchema, MergeFrom)]
  71#[serde(rename_all = "snake_case")]
  72pub enum EditPredictionProvider {
  73    None,
  74    #[default]
  75    Copilot,
  76    Supermaven,
  77    Zed,
  78    Codestral,
  79    Experimental(&'static str),
  80}
  81
  82pub const EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME: &str = "sweep";
  83pub const EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME: &str = "zeta2";
  84
  85impl<'de> Deserialize<'de> for EditPredictionProvider {
  86    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  87    where
  88        D: serde::Deserializer<'de>,
  89    {
  90        #[derive(Deserialize)]
  91        #[serde(rename_all = "snake_case")]
  92        pub enum Content {
  93            None,
  94            Copilot,
  95            Supermaven,
  96            Zed,
  97            Codestral,
  98            Experimental(String),
  99        }
 100
 101        Ok(match Content::deserialize(deserializer)? {
 102            Content::None => EditPredictionProvider::None,
 103            Content::Copilot => EditPredictionProvider::Copilot,
 104            Content::Supermaven => EditPredictionProvider::Supermaven,
 105            Content::Zed => EditPredictionProvider::Zed,
 106            Content::Codestral => EditPredictionProvider::Codestral,
 107            Content::Experimental(name)
 108                if name == EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME =>
 109            {
 110                EditPredictionProvider::Experimental(
 111                    EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
 112                )
 113            }
 114            Content::Experimental(name)
 115                if name == EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME =>
 116            {
 117                EditPredictionProvider::Experimental(
 118                    EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
 119                )
 120            }
 121            Content::Experimental(name) => {
 122                return Err(D::Error::custom(format!(
 123                    "Unknown experimental edit prediction provider: {}",
 124                    name
 125                )));
 126            }
 127        })
 128    }
 129}
 130
 131impl EditPredictionProvider {
 132    pub fn is_zed(&self) -> bool {
 133        match self {
 134            EditPredictionProvider::Zed => true,
 135            EditPredictionProvider::None
 136            | EditPredictionProvider::Copilot
 137            | EditPredictionProvider::Supermaven
 138            | EditPredictionProvider::Codestral
 139            | EditPredictionProvider::Experimental(_) => false,
 140        }
 141    }
 142}
 143
 144/// The contents of the edit prediction settings.
 145#[with_fallible_options]
 146#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
 147pub struct EditPredictionSettingsContent {
 148    /// A list of globs representing files that edit predictions should be disabled for.
 149    /// This list adds to a pre-existing, sensible default set of globs.
 150    /// Any additional ones you add are combined with them.
 151    pub disabled_globs: Option<Vec<String>>,
 152    /// The mode used to display edit predictions in the buffer.
 153    /// Provider support required.
 154    pub mode: Option<EditPredictionsMode>,
 155    /// Settings specific to GitHub Copilot.
 156    pub copilot: Option<CopilotSettingsContent>,
 157    /// Settings specific to Codestral.
 158    pub codestral: Option<CodestralSettingsContent>,
 159    /// Whether edit predictions are enabled in the assistant prompt editor.
 160    /// This has no effect if globally disabled.
 161    pub enabled_in_text_threads: Option<bool>,
 162}
 163
 164#[with_fallible_options]
 165#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
 166pub struct CopilotSettingsContent {
 167    /// HTTP/HTTPS proxy to use for Copilot.
 168    ///
 169    /// Default: none
 170    pub proxy: Option<String>,
 171    /// Disable certificate verification for the proxy (not recommended).
 172    ///
 173    /// Default: false
 174    pub proxy_no_verify: Option<bool>,
 175    /// Enterprise URI for Copilot.
 176    ///
 177    /// Default: none
 178    pub enterprise_uri: Option<String>,
 179}
 180
 181#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
 182pub struct CodestralSettingsContent {
 183    /// Model to use for completions.
 184    ///
 185    /// Default: "codestral-latest"
 186    #[serde(default)]
 187    pub model: Option<String>,
 188    /// Maximum tokens to generate.
 189    ///
 190    /// Default: 150
 191    #[serde(default)]
 192    pub max_tokens: Option<u32>,
 193    /// Api URL to use for completions.
 194    ///
 195    /// Default: "https://codestral.mistral.ai"
 196    #[serde(default)]
 197    pub api_url: Option<String>,
 198}
 199
 200/// The mode in which edit predictions should be displayed.
 201#[derive(
 202    Copy,
 203    Clone,
 204    Debug,
 205    Default,
 206    Eq,
 207    PartialEq,
 208    Serialize,
 209    Deserialize,
 210    JsonSchema,
 211    MergeFrom,
 212    strum::VariantArray,
 213    strum::VariantNames,
 214)]
 215#[serde(rename_all = "snake_case")]
 216pub enum EditPredictionsMode {
 217    /// If provider supports it, display inline when holding modifier key (e.g., alt).
 218    /// Otherwise, eager preview is used.
 219    #[serde(alias = "auto")]
 220    Subtle,
 221    /// Display inline when there are no language server completions available.
 222    #[default]
 223    #[serde(alias = "eager_preview")]
 224    Eager,
 225}
 226
 227/// Controls the soft-wrapping behavior in the editor.
 228#[derive(
 229    Copy,
 230    Clone,
 231    Debug,
 232    Serialize,
 233    Deserialize,
 234    PartialEq,
 235    Eq,
 236    JsonSchema,
 237    MergeFrom,
 238    strum::VariantArray,
 239    strum::VariantNames,
 240)]
 241#[serde(rename_all = "snake_case")]
 242pub enum SoftWrap {
 243    /// Prefer a single line generally, unless an overly long line is encountered.
 244    None,
 245    /// Deprecated: use None instead. Left to avoid breaking existing users' configs.
 246    /// Prefer a single line generally, unless an overly long line is encountered.
 247    PreferLine,
 248    /// Soft wrap lines that exceed the editor width.
 249    EditorWidth,
 250    /// Soft wrap lines at the preferred line length.
 251    PreferredLineLength,
 252    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
 253    Bounded,
 254}
 255
 256/// The settings for a particular language.
 257#[with_fallible_options]
 258#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
 259pub struct LanguageSettingsContent {
 260    /// How many columns a tab should occupy.
 261    ///
 262    /// Default: 4
 263    #[schemars(range(min = 1, max = 128))]
 264    pub tab_size: Option<NonZeroU32>,
 265    /// Whether to indent lines using tab characters, as opposed to multiple
 266    /// spaces.
 267    ///
 268    /// Default: false
 269    pub hard_tabs: Option<bool>,
 270    /// How to soft-wrap long lines of text.
 271    ///
 272    /// Default: none
 273    pub soft_wrap: Option<SoftWrap>,
 274    /// The column at which to soft-wrap lines, for buffers where soft-wrap
 275    /// is enabled.
 276    ///
 277    /// Default: 80
 278    pub preferred_line_length: Option<u32>,
 279    /// Whether to show wrap guides in the editor. Setting this to true will
 280    /// show a guide at the 'preferred_line_length' value if softwrap is set to
 281    /// 'preferred_line_length', and will show any additional guides as specified
 282    /// by the 'wrap_guides' setting.
 283    ///
 284    /// Default: true
 285    pub show_wrap_guides: Option<bool>,
 286    /// Character counts at which to show wrap guides in the editor.
 287    ///
 288    /// Default: []
 289    pub wrap_guides: Option<Vec<usize>>,
 290    /// Indent guide related settings.
 291    pub indent_guides: Option<IndentGuideSettingsContent>,
 292    /// Whether or not to perform a buffer format before saving.
 293    ///
 294    /// Default: on
 295    pub format_on_save: Option<FormatOnSave>,
 296    /// Whether or not to remove any trailing whitespace from lines of a buffer
 297    /// before saving it.
 298    ///
 299    /// Default: true
 300    pub remove_trailing_whitespace_on_save: Option<bool>,
 301    /// Whether or not to ensure there's a single newline at the end of a buffer
 302    /// when saving it.
 303    ///
 304    /// Default: true
 305    pub ensure_final_newline_on_save: Option<bool>,
 306    /// How to perform a buffer format.
 307    ///
 308    /// Default: auto
 309    pub formatter: Option<FormatterList>,
 310    /// Zed's Prettier integration settings.
 311    /// Allows to enable/disable formatting with Prettier
 312    /// and configure default Prettier, used when no project-level Prettier installation is found.
 313    ///
 314    /// Default: off
 315    pub prettier: Option<PrettierSettingsContent>,
 316    /// Whether to automatically close JSX tags.
 317    pub jsx_tag_auto_close: Option<JsxTagAutoCloseSettingsContent>,
 318    /// Whether to use language servers to provide code intelligence.
 319    ///
 320    /// Default: true
 321    pub enable_language_server: Option<bool>,
 322    /// The list of language servers to use (or disable) for this language.
 323    ///
 324    /// This array should consist of language server IDs, as well as the following
 325    /// special tokens:
 326    /// - `"!<language_server_id>"` - A language server ID prefixed with a `!` will be disabled.
 327    /// - `"..."` - A placeholder to refer to the **rest** of the registered language servers for this language.
 328    ///
 329    /// Default: ["..."]
 330    pub language_servers: Option<Vec<String>>,
 331    /// Controls where the `editor::Rewrap` action is allowed for this language.
 332    ///
 333    /// Note: This setting has no effect in Vim mode, as rewrap is already
 334    /// allowed everywhere.
 335    ///
 336    /// Default: "in_comments"
 337    pub allow_rewrap: Option<RewrapBehavior>,
 338    /// Controls whether edit predictions are shown immediately (true)
 339    /// or manually by triggering `editor::ShowEditPrediction` (false).
 340    ///
 341    /// Default: true
 342    pub show_edit_predictions: Option<bool>,
 343    /// Controls whether edit predictions are shown in the given language
 344    /// scopes.
 345    ///
 346    /// Example: ["string", "comment"]
 347    ///
 348    /// Default: []
 349    pub edit_predictions_disabled_in: Option<Vec<String>>,
 350    /// Whether to show tabs and spaces in the editor.
 351    pub show_whitespaces: Option<ShowWhitespaceSetting>,
 352    /// Visible characters used to render whitespace when show_whitespaces is enabled.
 353    ///
 354    /// Default: "•" for spaces, "→" for tabs.
 355    pub whitespace_map: Option<WhitespaceMapContent>,
 356    /// Whether to start a new line with a comment when a previous line is a comment as well.
 357    ///
 358    /// Default: true
 359    pub extend_comment_on_newline: Option<bool>,
 360    /// Inlay hint related settings.
 361    pub inlay_hints: Option<InlayHintSettingsContent>,
 362    /// Whether to automatically type closing characters for you. For example,
 363    /// when you type '(', Zed will automatically add a closing ')' at the correct position.
 364    ///
 365    /// Default: true
 366    pub use_autoclose: Option<bool>,
 367    /// Whether to automatically surround text with characters for you. For example,
 368    /// when you select text and type '(', Zed will automatically surround text with ().
 369    ///
 370    /// Default: true
 371    pub use_auto_surround: Option<bool>,
 372    /// Controls how the editor handles the autoclosed characters.
 373    /// When set to `false`(default), skipping over and auto-removing of the closing characters
 374    /// happen only for auto-inserted characters.
 375    /// Otherwise(when `true`), the closing characters are always skipped over and auto-removed
 376    /// no matter how they were inserted.
 377    ///
 378    /// Default: false
 379    pub always_treat_brackets_as_autoclosed: Option<bool>,
 380    /// Whether to use additional LSP queries to format (and amend) the code after
 381    /// every "trigger" symbol input, defined by LSP server capabilities.
 382    ///
 383    /// Default: true
 384    pub use_on_type_format: Option<bool>,
 385    /// Which code actions to run on save before the formatter.
 386    /// These are not run if formatting is off.
 387    ///
 388    /// Default: {} (or {"source.organizeImports": true} for Go).
 389    pub code_actions_on_format: Option<HashMap<String, bool>>,
 390    /// Whether to perform linked edits of associated ranges, if the language server supports it.
 391    /// For example, when editing opening <html> tag, the contents of the closing </html> tag will be edited as well.
 392    ///
 393    /// Default: true
 394    pub linked_edits: Option<bool>,
 395    /// Whether indentation should be adjusted based on the context whilst typing.
 396    ///
 397    /// Default: true
 398    pub auto_indent: Option<bool>,
 399    /// Whether indentation of pasted content should be adjusted based on the context.
 400    ///
 401    /// Default: true
 402    pub auto_indent_on_paste: Option<bool>,
 403    /// Task configuration for this language.
 404    ///
 405    /// Default: {}
 406    pub tasks: Option<LanguageTaskSettingsContent>,
 407    /// Whether to pop the completions menu while typing in an editor without
 408    /// explicitly requesting it.
 409    ///
 410    /// Default: true
 411    pub show_completions_on_input: Option<bool>,
 412    /// Whether to display inline and alongside documentation for items in the
 413    /// completions menu.
 414    ///
 415    /// Default: true
 416    pub show_completion_documentation: Option<bool>,
 417    /// Controls how completions are processed for this language.
 418    pub completions: Option<CompletionSettingsContent>,
 419    /// Preferred debuggers for this language.
 420    ///
 421    /// Default: []
 422    pub debuggers: Option<Vec<String>>,
 423    /// Whether to enable word diff highlighting in the editor.
 424    ///
 425    /// When enabled, changed words within modified lines are highlighted
 426    /// to show exactly what changed.
 427    ///
 428    /// Default: true
 429    pub word_diff_enabled: Option<bool>,
 430    /// Whether to use tree-sitter bracket queries to detect and colorize the brackets in the editor.
 431    ///
 432    /// Default: false
 433    pub colorize_brackets: Option<bool>,
 434}
 435
 436/// Controls how whitespace should be displayedin the editor.
 437#[derive(
 438    Copy,
 439    Clone,
 440    Debug,
 441    Serialize,
 442    Deserialize,
 443    PartialEq,
 444    Eq,
 445    JsonSchema,
 446    MergeFrom,
 447    strum::VariantArray,
 448    strum::VariantNames,
 449)]
 450#[serde(rename_all = "snake_case")]
 451pub enum ShowWhitespaceSetting {
 452    /// Draw whitespace only for the selected text.
 453    Selection,
 454    /// Do not draw any tabs or spaces.
 455    None,
 456    /// Draw all invisible symbols.
 457    All,
 458    /// Draw whitespaces at boundaries only.
 459    ///
 460    /// For a whitespace to be on a boundary, any of the following conditions need to be met:
 461    /// - It is a tab
 462    /// - It is adjacent to an edge (start or end)
 463    /// - It is adjacent to a whitespace (left or right)
 464    Boundary,
 465    /// Draw whitespaces only after non-whitespace characters.
 466    Trailing,
 467}
 468
 469#[with_fallible_options]
 470#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
 471pub struct WhitespaceMapContent {
 472    pub space: Option<char>,
 473    pub tab: Option<char>,
 474}
 475
 476/// The behavior of `editor::Rewrap`.
 477#[derive(
 478    Debug,
 479    PartialEq,
 480    Clone,
 481    Copy,
 482    Default,
 483    Serialize,
 484    Deserialize,
 485    JsonSchema,
 486    MergeFrom,
 487    strum::VariantArray,
 488    strum::VariantNames,
 489)]
 490#[serde(rename_all = "snake_case")]
 491pub enum RewrapBehavior {
 492    /// Only rewrap within comments.
 493    #[default]
 494    InComments,
 495    /// Only rewrap within the current selection(s).
 496    InSelections,
 497    /// Allow rewrapping anywhere.
 498    Anywhere,
 499}
 500
 501#[with_fallible_options]
 502#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
 503pub struct JsxTagAutoCloseSettingsContent {
 504    /// Enables or disables auto-closing of JSX tags.
 505    pub enabled: Option<bool>,
 506}
 507
 508/// The settings for inlay hints.
 509#[with_fallible_options]
 510#[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq, Eq)]
 511pub struct InlayHintSettingsContent {
 512    /// Global switch to toggle hints on and off.
 513    ///
 514    /// Default: false
 515    pub enabled: Option<bool>,
 516    /// Global switch to toggle inline values on and off when debugging.
 517    ///
 518    /// Default: true
 519    pub show_value_hints: Option<bool>,
 520    /// Whether type hints should be shown.
 521    ///
 522    /// Default: true
 523    pub show_type_hints: Option<bool>,
 524    /// Whether parameter hints should be shown.
 525    ///
 526    /// Default: true
 527    pub show_parameter_hints: Option<bool>,
 528    /// Whether other hints should be shown.
 529    ///
 530    /// Default: true
 531    pub show_other_hints: Option<bool>,
 532    /// Whether to show a background for inlay hints.
 533    ///
 534    /// If set to `true`, the background will use the `hint.background` color
 535    /// from the current theme.
 536    ///
 537    /// Default: false
 538    pub show_background: Option<bool>,
 539    /// Whether or not to debounce inlay hints updates after buffer edits.
 540    ///
 541    /// Set to 0 to disable debouncing.
 542    ///
 543    /// Default: 700
 544    pub edit_debounce_ms: Option<u64>,
 545    /// Whether or not to debounce inlay hints updates after buffer scrolls.
 546    ///
 547    /// Set to 0 to disable debouncing.
 548    ///
 549    /// Default: 50
 550    pub scroll_debounce_ms: Option<u64>,
 551    /// Toggles inlay hints (hides or shows) when the user presses the modifiers specified.
 552    /// If only a subset of the modifiers specified is pressed, hints are not toggled.
 553    /// If no modifiers are specified, this is equivalent to `null`.
 554    ///
 555    /// Default: null
 556    pub toggle_on_modifiers_press: Option<Modifiers>,
 557}
 558
 559/// The kind of an inlay hint.
 560#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 561pub enum InlayHintKind {
 562    /// An inlay hint for a type.
 563    Type,
 564    /// An inlay hint for a parameter.
 565    Parameter,
 566}
 567
 568impl InlayHintKind {
 569    /// Returns the [`InlayHintKind`]fromthe given name.
 570    ///
 571    /// Returns `None` if `name` does not match any of the expected
 572    /// string representations.
 573    pub fn from_name(name: &str) -> Option<Self> {
 574        match name {
 575            "type" => Some(InlayHintKind::Type),
 576            "parameter" => Some(InlayHintKind::Parameter),
 577            _ => None,
 578        }
 579    }
 580
 581    /// Returns the name of this [`InlayHintKind`].
 582    pub fn name(&self) -> &'static str {
 583        match self {
 584            InlayHintKind::Type => "type",
 585            InlayHintKind::Parameter => "parameter",
 586        }
 587    }
 588}
 589
 590/// Controls how completions are processed for this language.
 591#[with_fallible_options]
 592#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom, Default)]
 593#[serde(rename_all = "snake_case")]
 594pub struct CompletionSettingsContent {
 595    /// Controls how words are completed.
 596    /// For large documents, not all words may be fetched for completion.
 597    ///
 598    /// Default: `fallback`
 599    pub words: Option<WordsCompletionMode>,
 600    /// How many characters has to be in the completions query to automatically show the words-based completions.
 601    /// Before that value, it's still possible to trigger the words-based completion manually with the corresponding editor command.
 602    ///
 603    /// Default: 3
 604    pub words_min_length: Option<u32>,
 605    /// Whether to fetch LSP completions or not.
 606    ///
 607    /// Default: true
 608    pub lsp: Option<bool>,
 609    /// When fetching LSP completions, determines how long to wait for a response of a particular server.
 610    /// When set to 0, waits indefinitely.
 611    ///
 612    /// Default: 0
 613    pub lsp_fetch_timeout_ms: Option<u64>,
 614    /// Controls how LSP completions are inserted.
 615    ///
 616    /// Default: "replace_suffix"
 617    pub lsp_insert_mode: Option<LspInsertMode>,
 618}
 619
 620#[derive(
 621    Copy,
 622    Clone,
 623    Debug,
 624    Serialize,
 625    Deserialize,
 626    PartialEq,
 627    Eq,
 628    JsonSchema,
 629    MergeFrom,
 630    strum::VariantArray,
 631    strum::VariantNames,
 632)]
 633#[serde(rename_all = "snake_case")]
 634pub enum LspInsertMode {
 635    /// Replaces text before the cursor, using the `insert` range described in the LSP specification.
 636    Insert,
 637    /// Replaces text before and after the cursor, using the `replace` range described in the LSP specification.
 638    Replace,
 639    /// Behaves like `"replace"` if the text that would be replaced is a subsequence of the completion text,
 640    /// and like `"insert"` otherwise.
 641    ReplaceSubsequence,
 642    /// Behaves like `"replace"` if the text after the cursor is a suffix of the completion, and like
 643    /// `"insert"` otherwise.
 644    ReplaceSuffix,
 645}
 646
 647/// Controls how document's words are completed.
 648#[derive(
 649    Copy,
 650    Clone,
 651    Debug,
 652    Serialize,
 653    Deserialize,
 654    PartialEq,
 655    Eq,
 656    JsonSchema,
 657    MergeFrom,
 658    strum::VariantArray,
 659    strum::VariantNames,
 660)]
 661#[serde(rename_all = "snake_case")]
 662pub enum WordsCompletionMode {
 663    /// Always fetch document's words for completions along with LSP completions.
 664    Enabled,
 665    /// Only if LSP response errors or times out,
 666    /// use document's words to show completions.
 667    Fallback,
 668    /// Never fetch or complete document's words for completions.
 669    /// (Word-based completions can still be queried via a separate action)
 670    Disabled,
 671}
 672
 673/// Allows to enable/disable formatting with Prettier
 674/// and configure default Prettier, used when no project-level Prettier installation is found.
 675/// Prettier formatting is disabled by default.
 676#[with_fallible_options]
 677#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
 678pub struct PrettierSettingsContent {
 679    /// Enables or disables formatting with Prettier for a given language.
 680    pub allowed: Option<bool>,
 681
 682    /// Forces Prettier integration to use a specific parser name when formatting files with the language.
 683    pub parser: Option<String>,
 684
 685    /// Forces Prettier integration to use specific plugins when formatting files with the language.
 686    /// The default Prettier will be installed with these plugins.
 687    pub plugins: Option<HashSet<String>>,
 688
 689    /// Default Prettier options, in the format as in package.json section for Prettier.
 690    /// If project installs Prettier via its package.json, these options will be ignored.
 691    #[serde(flatten)]
 692    pub options: Option<HashMap<String, serde_json::Value>>,
 693}
 694
 695/// TODO: this should just be a bool
 696/// Controls the behavior of formatting files when they are saved.
 697#[derive(
 698    Debug,
 699    Clone,
 700    Copy,
 701    PartialEq,
 702    Eq,
 703    Serialize,
 704    Deserialize,
 705    JsonSchema,
 706    MergeFrom,
 707    strum::VariantArray,
 708    strum::VariantNames,
 709)]
 710#[serde(rename_all = "lowercase")]
 711pub enum FormatOnSave {
 712    /// Files should be formatted on save.
 713    On,
 714    /// Files should not be formatted on save.
 715    Off,
 716}
 717
 718/// Controls which formatters should be used when formatting code.
 719#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 720#[serde(untagged)]
 721pub enum FormatterList {
 722    Single(Formatter),
 723    Vec(Vec<Formatter>),
 724}
 725
 726impl Default for FormatterList {
 727    fn default() -> Self {
 728        Self::Single(Formatter::default())
 729    }
 730}
 731
 732impl AsRef<[Formatter]> for FormatterList {
 733    fn as_ref(&self) -> &[Formatter] {
 734        match &self {
 735            Self::Single(single) => std::slice::from_ref(single),
 736            Self::Vec(v) => v,
 737        }
 738    }
 739}
 740
 741/// Controls which formatter should be used when formatting code. If there are multiple formatters, they are executed in the order of declaration.
 742#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 743#[serde(rename_all = "snake_case")]
 744pub enum Formatter {
 745    /// Format files using Zed's Prettier integration (if applicable),
 746    /// or falling back to formatting via language server.
 747    #[default]
 748    Auto,
 749    /// Format code using Zed's Prettier integration.
 750    Prettier,
 751    /// Format code using an external command.
 752    External {
 753        /// The external program to run.
 754        command: Arc<str>,
 755        /// The arguments to pass to the program.
 756        arguments: Option<Arc<[String]>>,
 757    },
 758    /// Files should be formatted using a code action executed by language servers.
 759    CodeAction(String),
 760    /// Format code using a language server.
 761    #[serde(untagged)]
 762    LanguageServer(LanguageServerFormatterSpecifier),
 763}
 764
 765#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 766#[serde(
 767    rename_all = "snake_case",
 768    // allow specifying language servers as "language_server" or {"language_server": {"name": ...}}
 769    from = "LanguageServerVariantContent",
 770    into = "LanguageServerVariantContent"
 771)]
 772pub enum LanguageServerFormatterSpecifier {
 773    Specific {
 774        name: String,
 775    },
 776    #[default]
 777    Current,
 778}
 779
 780impl From<LanguageServerVariantContent> for LanguageServerFormatterSpecifier {
 781    fn from(value: LanguageServerVariantContent) -> Self {
 782        match value {
 783            LanguageServerVariantContent::Specific {
 784                language_server: LanguageServerSpecifierContent { name: Some(name) },
 785            } => Self::Specific { name },
 786            _ => Self::Current,
 787        }
 788    }
 789}
 790
 791impl From<LanguageServerFormatterSpecifier> for LanguageServerVariantContent {
 792    fn from(value: LanguageServerFormatterSpecifier) -> Self {
 793        match value {
 794            LanguageServerFormatterSpecifier::Specific { name } => Self::Specific {
 795                language_server: LanguageServerSpecifierContent { name: Some(name) },
 796            },
 797            LanguageServerFormatterSpecifier::Current => {
 798                Self::Current(CurrentLanguageServerContent::LanguageServer)
 799            }
 800        }
 801    }
 802}
 803
 804#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 805#[serde(rename_all = "snake_case", untagged)]
 806enum LanguageServerVariantContent {
 807    /// Format code using a specific language server.
 808    Specific {
 809        language_server: LanguageServerSpecifierContent,
 810    },
 811    /// Format code using the current language server.
 812    Current(CurrentLanguageServerContent),
 813}
 814
 815#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 816#[serde(rename_all = "snake_case")]
 817enum CurrentLanguageServerContent {
 818    #[default]
 819    LanguageServer,
 820}
 821
 822#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom)]
 823#[serde(rename_all = "snake_case")]
 824struct LanguageServerSpecifierContent {
 825    /// The name of the language server to format with
 826    name: Option<String>,
 827}
 828
 829/// The settings for indent guides.
 830#[with_fallible_options]
 831#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom)]
 832pub struct IndentGuideSettingsContent {
 833    /// Whether to display indent guides in the editor.
 834    ///
 835    /// Default: true
 836    pub enabled: Option<bool>,
 837    /// The width of the indent guides in pixels, between 1 and 10.
 838    ///
 839    /// Default: 1
 840    pub line_width: Option<u32>,
 841    /// The width of the active indent guide in pixels, between 1 and 10.
 842    ///
 843    /// Default: 1
 844    pub active_line_width: Option<u32>,
 845    /// Determines how indent guides are colored.
 846    ///
 847    /// Default: Fixed
 848    pub coloring: Option<IndentGuideColoring>,
 849    /// Determines how indent guide backgrounds are colored.
 850    ///
 851    /// Default: Disabled
 852    pub background_coloring: Option<IndentGuideBackgroundColoring>,
 853}
 854
 855/// The task settings for a particular language.
 856#[with_fallible_options]
 857#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize, JsonSchema, MergeFrom)]
 858pub struct LanguageTaskSettingsContent {
 859    /// Extra task variables to set for a particular language.
 860    pub variables: Option<HashMap<String, String>>,
 861    pub enabled: Option<bool>,
 862    /// Use LSP tasks over Zed language extension ones.
 863    /// If no LSP tasks are returned due to error/timeout or regular execution,
 864    /// Zed language extension tasks will be used instead.
 865    ///
 866    /// Other Zed tasks will still be shown:
 867    /// * Zed task from either of the task config file
 868    /// * Zed task from history (e.g. one-off task was spawned before)
 869    pub prefer_lsp: Option<bool>,
 870}
 871
 872/// Map from language name to settings.
 873#[with_fallible_options]
 874#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
 875pub struct LanguageToSettingsMap(pub HashMap<SharedString, LanguageSettingsContent>);
 876
 877/// Determines how indent guides are colored.
 878#[derive(
 879    Default,
 880    Debug,
 881    Copy,
 882    Clone,
 883    PartialEq,
 884    Eq,
 885    Serialize,
 886    Deserialize,
 887    JsonSchema,
 888    MergeFrom,
 889    strum::VariantArray,
 890    strum::VariantNames,
 891)]
 892#[serde(rename_all = "snake_case")]
 893pub enum IndentGuideColoring {
 894    /// Do not render any lines for indent guides.
 895    Disabled,
 896    /// Use the same color for all indentation levels.
 897    #[default]
 898    Fixed,
 899    /// Use a different color for each indentation level.
 900    IndentAware,
 901}
 902
 903/// Determines how indent guide backgrounds are colored.
 904#[derive(
 905    Default,
 906    Debug,
 907    Copy,
 908    Clone,
 909    PartialEq,
 910    Eq,
 911    Serialize,
 912    Deserialize,
 913    JsonSchema,
 914    MergeFrom,
 915    strum::VariantArray,
 916    strum::VariantNames,
 917)]
 918#[serde(rename_all = "snake_case")]
 919pub enum IndentGuideBackgroundColoring {
 920    /// Do not render any background for indent guides.
 921    #[default]
 922    Disabled,
 923    /// Use a different color for each indentation level.
 924    IndentAware,
 925}
 926
 927#[cfg(test)]
 928mod test {
 929
 930    use crate::{ParseStatus, fallible_options};
 931
 932    use super::*;
 933
 934    #[test]
 935    fn test_formatter_deserialization() {
 936        let raw_auto = "{\"formatter\": \"auto\"}";
 937        let settings: LanguageSettingsContent = serde_json::from_str(raw_auto).unwrap();
 938        assert_eq!(
 939            settings.formatter,
 940            Some(FormatterList::Single(Formatter::Auto))
 941        );
 942        let raw = "{\"formatter\": \"language_server\"}";
 943        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
 944        assert_eq!(
 945            settings.formatter,
 946            Some(FormatterList::Single(Formatter::LanguageServer(
 947                LanguageServerFormatterSpecifier::Current
 948            )))
 949        );
 950
 951        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}]}";
 952        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
 953        assert_eq!(
 954            settings.formatter,
 955            Some(FormatterList::Vec(vec![Formatter::LanguageServer(
 956                LanguageServerFormatterSpecifier::Current
 957            )]))
 958        );
 959        let raw = "{\"formatter\": [{\"language_server\": {\"name\": null}}, \"language_server\", \"prettier\"]}";
 960        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
 961        assert_eq!(
 962            settings.formatter,
 963            Some(FormatterList::Vec(vec![
 964                Formatter::LanguageServer(LanguageServerFormatterSpecifier::Current),
 965                Formatter::LanguageServer(LanguageServerFormatterSpecifier::Current),
 966                Formatter::Prettier
 967            ]))
 968        );
 969
 970        let raw = "{\"formatter\": [{\"language_server\": {\"name\": \"ruff\"}}, \"prettier\"]}";
 971        let settings: LanguageSettingsContent = serde_json::from_str(raw).unwrap();
 972        assert_eq!(
 973            settings.formatter,
 974            Some(FormatterList::Vec(vec![
 975                Formatter::LanguageServer(LanguageServerFormatterSpecifier::Specific {
 976                    name: "ruff".to_string()
 977                }),
 978                Formatter::Prettier
 979            ]))
 980        );
 981
 982        assert_eq!(
 983            serde_json::to_string(&LanguageServerFormatterSpecifier::Current).unwrap(),
 984            "\"language_server\"",
 985        );
 986    }
 987
 988    #[test]
 989    fn test_formatter_deserialization_invalid() {
 990        let raw_auto = "{\"formatter\": {}}";
 991        let (_, result) = fallible_options::parse_json::<LanguageSettingsContent>(raw_auto);
 992        assert!(matches!(result, ParseStatus::Failed { .. }));
 993    }
 994
 995    #[test]
 996    fn test_prettier_options() {
 997        let raw_prettier = r#"{"allowed": false, "tabWidth": 4, "semi": false}"#;
 998        let result = serde_json::from_str::<PrettierSettingsContent>(raw_prettier)
 999            .expect("Failed to parse prettier options");
1000        assert!(
1001            result
1002                .options
1003                .as_ref()
1004                .expect("options were flattened")
1005                .contains_key("semi")
1006        );
1007        assert!(
1008            result
1009                .options
1010                .as_ref()
1011                .expect("options were flattened")
1012                .contains_key("tabWidth")
1013        );
1014    }
1015}