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