language.rs

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