language.rs

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