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