language.rs

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