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